C 分叉后,父级永远不会执行
我正在尝试熟悉管道,我编写了一个相当愚蠢的parrot程序,它基本上接收键盘输入,然后显示完全相同的内容:C 分叉后,父级永远不会执行,c,fork,C,Fork,我正在尝试熟悉管道,我编写了一个相当愚蠢的parrot程序,它基本上接收键盘输入,然后显示完全相同的内容: if (pipe(fd) < 0) { perror("Pipe"); exit(1); } if ( ( pid = fork() < 0 ) ) { perror("Fork"); exit(1); } if ( pid > 0 ) //If I'm the paren
if (pipe(fd) < 0) {
perror("Pipe");
exit(1);
}
if ( ( pid = fork() < 0 ) ) {
perror("Fork");
exit(1);
}
if ( pid > 0 ) //If I'm the parent...
{
printf("Parent!");
close(fd[0]);
//as long as something is typed in and that something isn't
// the word "stop"
while (((n = read(STDIN_FILENO, buffer, BUFFERSIZE)) > 0) &&
(strncmp(buffer, "stop", 4) != 0))
{
//shove all the buffer content into the pipe
write(fd[1], buffer, BUFFERSIZE);
}
}
else //If I am the child...
{
printf("Child!");
close(fd[1]);
//as long as there's something to read
while (pipe_read = read(fd[0], buf, sizeof(buf)) > 0)
{
//display on the screen!
write(STDOUT_FILENO, buf, pipe_read);
}
}
if(管道(fd)<0){
佩罗(“管道”);
出口(1);
}
如果((pid=fork()<0)){
佩罗尔(“福克”);
出口(1);
}
如果(pid>0)//如果我是家长。。。
{
printf(“父!”);
关闭(fd[0]);
//只要输入了某个内容,而该内容不是
//“停止”一词
而((n=read(STDIN_FILENO,buffer,BUFFERSIZE))>0)和
(strncmp(缓冲区,“停止”,4)!=0)
{
//将所有缓冲区内容推入管道
写入(fd[1],缓冲区,缓冲区大小);
}
}
否则//如果我是孩子。。。
{
printf(“孩子!”);
关闭(fd[1]);
//只要有东西可以读
而(pipe_read=read(fd[0],buf,sizeof(buf))>0)
{
//在屏幕上显示!
写入(标准输出文件号、buf、管道读取);
}
}
我明白了为什么这个程序不参与循环,这是因为父级从不执行,因此我得到了子级!孩子代码>作为输出,我不知道为什么 变化
if ( ( pid = fork() < 0 ) )
if((pid=fork()<0))
与
if((pid=fork())<0)
在没有右括号的情况下,pid被设置为(fork()<0)
,这是0
更改
if ( ( pid = fork() < 0 ) )
if((pid=fork()<0))
与
if((pid=fork())<0)
在没有右括号的情况下,pid
被设置为(fork()<0)
,这是0
如果您得到两个表示Child的print语句,听起来好像两个进程都进入了else语句。如果您得到两个表示Child的print语句,听起来这两个进程都将进入else语句。+1,但没有转换。fork()<0
的结果是0。我忘了c
没有布尔值@蓝色,自1999年以来,C已\u Bool
。该类型有两个值0
和1
,标题stdbool.h
有两个宏false
和true
,对这些值求值。@jens do比较运算符返回一个_Bool?@蓝色,不,它是int
,但仅限于值0
和1
+1,但是没有转换。fork()<0
的结果是0。我忘了c
没有布尔值@蓝色,自1999年以来,C已\u Bool
。类型有两个值0
和1
,标题stdbool.h
有两个宏false
和true
,它们对这些值求值。@jens do比较运算符返回一个_Bool?@蓝色,不,它是int
,但仅限于值0
和1
。