gpt4 book ai didi

c - 将子进程标准输出重定向到 C 中的管道

转载 作者:行者123 更新时间:2023-11-30 16:38:23 31 4
gpt4 key购买 nike

我尝试理解将子进程标准输出重定向到管道的主题,父进程可以读取它并面临非常奇怪的行为。在示例中,父进程派生了 3 个子进程,这些子进程执行简单的文件搜索并想要获取输出。我只收到第一个结果。这个例子可能有什么问题?

代码如下所示:

char * searches[] = {
".bashrc",
"NM34_x64.exe",
"blacklist.sh"
};
int fd[2];
if (pipe(fd) == -1) {
error("Can't create the pipe");
}
__pid_t pids[sizeof(searches)/sizeof(char*)];

for(int i = 0; i < sizeof(searches)/sizeof(char*); i++){
__pid_t pid = fork();

switch (pid) {
case -1 :
// ERROR CASE
error("Failed to make a child process");
break;
case 0 :
// CHILD CASE
// 1. Redirect Standard Output to pipe
dup2(fd[1], 1);
close(fd[0]);
// 2. Execute command
if (execl("/usr/bin/find", "/usr/bin/find", "/home", "-name", searches[i], NULL) == -1)
error("Failed to execute the command in the child process");
break;
default:
// PARENT CASE
printf("Created child process with pid %d\n", pid);
pids[i] = pid;
// 1. Wait for PID to finish
int status;
waitpid(pids[0], &status, 0);
if (status == -1)
error("Failed to wait the child PID");
printf("Process %d finish his work\n", pids[i]);
// 2. Redirect pipe to Standard Input
dup2(fd[0],0);
close(fd[1]);
// 3. Read Standard Input
char line[255];
while (fgets(line,255,stdin)) {
printf("%s", line);
}
break;
}
}
return 0;

这是输出:

Created child process with pid 5063
Process 5063 finish his work
/home/user/.bashrc
Created child process with pid 5064
Process 5064 finish his work
Created child process with pid 5065
Process 5065 finish his work

最佳答案

当您使用管道进行进程间通信时,直接从管道读取输入到主进程,而不是再次将其重定向到标准输入并在主进程中读取。

关于c - 将子进程标准输出重定向到 C 中的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515399/

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