linux C语言 管道pipe的问题

初识linux,不太懂这道题,请高手写下过程供分析,最好有注释,不胜感激...

程序要求:生成新的进程,把从命令行输入的信息从子进程送到父进程的程序。unipipe
如下:
$ ./unipipe [strings(CtoP}]
$
$ ./twopipe “Hello, This is Child process”
<PARENT> message from child: Hello, This is Child process
要点:
如图所示,利用fork()等,使用单方向管道。

注:此题是翻译过来的,语言有可能组织的不到位,见谅

第1个回答  2010-06-23
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, const char *argv[])
{
int fd[2];
int pid;

if (argc != 2)
{
printf("Usage:\n\t%s string\n", argv[0]);
return 1;
}

if (pipe(fd) < 0)
{
printf("Unable to create pipe!\n");
return 1;
}

// fork child process
pid = fork();

if (pid == 0) //child
{
close(fd[0]); //close read end
write(fd[1], argv[1], strlen(argv[1])); //write message
close(fd[1]); //close before exit
}
else if (pid > 0) //parent
{
char buf[1024];
int len;

close(fd[1]); //close write end
len = read(fd[0], buf, sizeof(buf)); //read from the pipe
buf[len] ='\0';
printf("<PARENT> message from child: %s\n", buf);
wait(NULL); //wait for child exit
close(fd[0]); //close before exit
}
else
{
printf("Unable to fork!\n");
return 1;
}

return 0;
}本回答被提问者采纳
第2个回答  2021-04-12

关于Linux管道的一切

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网