gpt4 book ai didi

c - 使用子进程和父进程写入管道

转载 作者:行者123 更新时间:2023-12-04 11:54:19 24 4
gpt4 key购买 nike

我正在尝试创建一个调用排序的子项。 parent 通过管道向 child 发送数据。我的代码编译并运行,但没有输出。我究竟做错了什么?我没有正确关闭管道、写入管道或正确输出数据吗?

[eddit] 在我的系统上我需要调用/bin/sort 而不是/usr/bin/sort!

#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <ctype.h>

int main(void){
int pipes[2];
pid_t pid;
FILE *stream;

if(pipe(pipes) == -1)
printf("could not create pipe\n");

switch(fork()){
case -1:
fprintf(stderr, "error forking\n");
break;
case 0:
dup2(pipes[0], STDIN_FILENO);

pid = getpid();
printf("in child, pid=%d\n");

if(close(pipes[1]) == -1)
fprintf(stderr,"err closing write end pid=%d\n", pid);

execl("/usr/bin/sort", "sort", (char*) NULL);
break;
default:
stream = fdopen(pipes[1], "w");
pid = getpid();
printf("in parent, pid=%d\n", pid);

if (stream == NULL)
fprintf(stderr, "could not create file streami\n");

if(close(pipes[0]) == -1)
printf("err closing read end pid=%d\n");

fputs("bob\n",stream);
fputs("cat\n",stream);
fputs("ace\n",stream);
fputs("dog\n",stream);

if(fclose(stream) == EOF)
fprintf(stderr, "error while closing stream\n");
break;
}
return 0;
}

[edit] 这是我的工作代码。谢谢大家

#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void){
int pipes[2];
pid_t pid;
FILE *stream;

int stat;
if(pipe(pipes) == -1)
printf("could not create pipe\n");

switch(fork()){
case -1:
fprintf(stderr, "error forking\n");
break;
case 0:
dup2(pipes[0], STDIN_FILENO);

pid = getpid();
printf("in child, pid=%d\n", pid);

if(close(pipes[1]) == -1)
fprintf(stderr,"err closing write end pid=%d\n", pid);

if(close(pipes[0]) == -1)
fprintf(stderr,"err closing write end pid=%d\n", pid);

execl("/bin/sort", "sort", (char*) NULL);
exit(EXIT_FAILURE);
break;
default:
stream = fdopen(pipes[1], "w");
pid = getpid();
printf("in parent, pid=%d\n", pid);

if (stream == NULL)
fprintf(stderr, "could not create file streami\n");

if(close(pipes[0]) == -1)
printf("err closing read end pid=%d\n");

fputs("bob\n",stream);
fputs("cat\n",stream);
fputs("ace\n",stream);
fputs("dog\n",stream);

if(fclose(stream) == EOF)
fprintf(stderr, "error while closing stream\n");
break;
}

wait(&stat);
return 0;
}

最佳答案

您的代码中肯定没有足够的 close() 调用,这将锁定进程。

伪代码:

Create pipe
Fork
In parent:
Close read end of pipe
Write data to be sorted down write end of pipe
Close write end of pipe
Wait for child to die
In child
Close write end of pipe
Duplicate read end of pipe to stdin
Close read end of pipe
Exec the sort program
Exit with an error if the exec returns

请注意,伪代码最终关闭了管道的所有四个端点——父端的两端和子端的两端。如果不这样做,就会陷入僵局。

关于c - 使用子进程和父进程写入管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9255425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com