我有以下代码:
int pfds[2], pid;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pfds) < 0) {
goto error;
}
if ((pid = fork()) == -1)
goto error;
if (pid == 0) {
/* child */
close(pfds[1]);
dup2(pfds[0], 1);
close(pfds[0]);
const char *argv[5];
int i = 0;
argv[i++] = "/bin/sh";
argv[i++] = "/sbin/script.sh";
argv[i++] = NULL;
execvp(argv[0], (char **) argv);
exit(ESRCH);
}
close(pfds[0]);
s.stream.string_data = true;
s.stream.notify_read = client_read_cb;
ustream_fd_init(&s, pfds[1]);
脚本返回一个字符串(用echo
命令打印),标记脚本加载结束。
如何读取/sbin/script.sh
返回的字符串?
答案 0 :(得分:1)
基本上你错过了执行execv的子进程和执行阅读的父进程之间的区别:
char readbuffer[100];
if(pid == 0)
...
else
{
close(pdfs[0];
nbytes = read(pfds[1], readbuffer, sizeof(readbuffer));
}
但是如果你只是想等待脚本结束,你可以在子进程上执行wait_pid。