我有以下代码,我在其中使用 fork 启动我的脚本。该脚本正在监听标准输入。我尝试通过管道向 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");
}