我有以下代码,我使用fork来启动我的脚本。脚本正在侦听stdin。我尝试通过管道将数据发送到myscript,但是scipt没有从C获取数据。我在代码中遗漏了什么?
static int pfds_in[2], pfds_out[2];
void external_init()
{
int pid;
if (pipe(pfds_in) < 0)
return;
if (pipe(pfds_out) < 0)
return;
if ((pid = fork()) == -1)
goto error;
if (pid == 0) {
/* child */
close(pfds_in[0]);
dup2(pfds_in[1], 1);
close(pfds_in[1]);
close(pfds_out[0]);
dup2(pfds_out[1], 0);
close(pfds_out[1]);
const char *argv[5];
int i = 0;
argv[i++] = "/bin/sh";
argv[i++] = fc_script;
argv[i++] = "--json";
argv[i++] = "json_continuous_input";
argv[i++] = NULL;
execvp(argv[0], (char **) argv);
exit(ESRCH);
}
close(pfds_in[1]);
close(pfds_out[1]);
return;
error:
exit(EXIT_FAILURE);
}
static void external_write_pipe_output(const char *msg)
{
char *value = NULL;
int i=0, len;
asprintf(&value, "%s\n", msg);
if (write(pfds_out[0], value, strlen(value)) == -1) {
perror("Error occured when trying to write to the pipe");
}
free(value);
}
int main()
{
external_init();
external_write_pipe_output("any");
}
答案 0 :(得分:1)
您从pipe()获得的两个文件描述符都不匹配。 pfds_in[0]
用于阅读,因此您必须使用dup2( pfds_in[0], 0 )
在您的孩子和使用pfds_in[1]
写入管道的父级中使用dup( ..., 1 )
。
答案 1 :(得分:0)
你的管道末端混乱。
在孩子中你应该:
close(pfds_in[0]);
dup2(pfds_in[1], 1);
close(pfds_in[1]);
close(pfds_out[1]);
dup2(pfds_out[0], 0);
close(pfds_out[0]);
在父母身上:
close(pfds_in[1]);
close(pfds_out[0]);