gpt4 book ai didi

linux - 子进程无法从父进程写入的标准输入中获取输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:49 24 4
gpt4 key购买 nike

在子进程中,我使用 execl() 来执行一个程序“test1”,其中包含来自标准输入的输入。但是,stdin 的输入无法传递给“test1”,但可以用于“sort”命令。

example.c

#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
int fds[2]; // an array that will hold two file descriptors
pipe(fds); // populates fds with two file descriptors
pid_t pid = fork(); // create child process that is a clone of the parent

if (pid == 0) { // if pid == 0, then this is the child process
dup2(fds[0], STDIN_FILENO); // fds[0] (the read end of pipe) donates its data to file descriptor 0
close(fds[0]); // file descriptor no longer needed in child since stdin is a copy
close(fds[1]); // file descriptor unused in child
//if (execl("/usr/bin/sort", "sort", (char *)0) < 0) exit(0);//working
if (execl("./test1", "test1", (char *)0) < 0) exit(0);//not working
}

// if we reach here, we are in parent process
close(fds[0]); // file descriptor unused in parent
const char *words[] = {"pear", "peach", "apple"};
// write input to the writable file descriptor so it can be read in from child:
size_t numwords = sizeof(words)/sizeof(words[0]);
for (size_t i = 0; i < numwords; i++) {
dprintf(fds[1], "%s\n", words[i]);
}

// send EOF so child can continue (child blocks until all input has been processed):
close(fds[1]);

int status;
pid_t wpid = waitpid(pid, &status, 0); // wait for child to finish before exiting
return wpid == pid && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

对于“排序”命令,输出是:

$ ./example
apple
peach
pear

对于“test1”,输出是:

$ ./example
hello!
test1

如果它对“test1”有效,输出应该是:

$ ./test1 pear peach apple
hello!
./test1
pear
peach
apple

test1.c

#include<stdio.h> 
#include<stdlib.h>

int main(int argc, char** argv){
printf("hello!\n");
for(int i = 0; i < argc; i++){
printf("%s\n", argv[i]);
}
return 0;
}

我做错了什么?

最佳答案

test1 不读取任何输入,因此将输入传递给它不起作用。

要获得示例输出,请使用 test1 execl cat。

关于linux - 子进程无法从父进程写入的标准输入中获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667822/

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