Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用管道和叉子时_C_Linux_Unix_Pipe_System Calls - Fatal编程技术网

C 使用管道和叉子时

C 使用管道和叉子时,c,linux,unix,pipe,system-calls,C,Linux,Unix,Pipe,System Calls,我有一个简单的程序(maximum1)可以打印文件中的最大数字。挑战是使用分叉和管道以多个进程运行多个文件,并从这些文件中打印最大数量的文件。我把第一个程序放下,这样它就能打印出数字,但当我使用第二个程序(maximum2)时,我得到的数字比文件中的数字要大 我认为问题在于我使用管道或者不理解num1的传输。谢谢你的帮助 if ((childpid1 = fork()) < 0) { perror("Fork1 Error.\n"); } else if (childpid1

我有一个简单的程序(maximum1)可以打印文件中的最大数字。挑战是使用分叉和管道以多个进程运行多个文件,并从这些文件中打印最大数量的文件。我把第一个程序放下,这样它就能打印出数字,但当我使用第二个程序(maximum2)时,我得到的数字比文件中的数字要大

我认为问题在于我使用管道或者不理解num1的传输。谢谢你的帮助

  if ((childpid1 = fork()) < 0) {
    perror("Fork1 Error.\n");
} else if (childpid1 == 0) {      //Child Code

 close(fd[0]);
 dup2(fd[1], 1);
 dup2(fd[1], 2);
 close(fd[1]);

 execl ("max1", "max1", argv[1], NULL);
 perror("Failed Exec.\n"); //Make sure Execl works

} else {              //Parent Code
 waitpid(childpid1, &status, 0);
 char buffer[1024];

 close(fd[0]);

 read(fd[0], buffer, sizeof(buffer));

 sscanf( buffer, "%d", &num1);
 printf("%d\n", num1);
}
if((childpid1=fork())<0){
perror(“Fork1错误。\n”);
}如果(childpid1==0){//子代码
关闭(fd[0]);
dup2(fd[1],1);
dup2(fd[1,2]);
关闭(fd[1]);
execl(“max1”,“max1”,argv[1],NULL);
perror(“失败的Exec。\n”);//确保Exec工作
}else{//父代码
waitpid(childpid1和status,0);
字符缓冲区[1024];
关闭(fd[0]);
读取(fd[0],缓冲区,sizeof(缓冲区));
sscanf(缓冲区、%d、&num1);
printf(“%d\n”,num1);
}

在父进程的代码上,您可以执行以下操作:

//Parent Code
waitpid(childpid1, &status, 0);
char buffer[1024];

close(fd[0]);

read(fd[0], buffer, sizeof(buffer));

sscanf(buffer, "%d", &num1);
printf("%d\n", num1);
因此,您关闭
fd[0]
,我猜这是管道的读取端,然后尝试从中读取

该读数将返回一个
EBADF
错误,您永远不会检查该错误。所以您可能只是在输出上打印垃圾

将您的
读取(…)
更改为:

if (read(fd[0], buffer, sizeof(buffer) < 0) {
    perror("read");
    exit(EXIT_FAILURE);
}

请记住检查系统调用的返回值有多么重要。

谢谢!没看到我换了。
if (close(fd[1]) < 0) {
    perror("close");
    exit(EXIT_FAILURE);
}