我有以下通过 fork 和 execvp 执行命令的函数。我在 fork 中启动的脚本正在侦听输入数据。如何将数据发送到 myscript?
int external_command()
{
int pfds[2];
if (pipe(pfds) < 0)
return -1;
if ((uproc.pid = fork()) == -1)
return -1;
if (uproc.pid == 0) {
/* child */
const char *argv[4];
int i = 0;
argv[i++] = "/bin/sh";
argv[i++] = "myscript.sh";
argv[i++] = NULL;
close(pfds[0]);
dup2(pfds[1], 1);
close(pfds[1]);
execvp(argv[0], (char **) argv);
exit(ESRCH);
} else if (uproc.pid < 0)
return -1;
/* parent */
close(pfds[1]);
int status;
while (wait(&status) != uproc.pid) {
DD("waiting for child to exit");
}
char buffer[64];
ssize_t rxed;
char *c;
int t;
//read from fork pipe
*value = NULL;
while ((rxed = read(pfds[0], buffer, sizeof(buffer))) > 0) {
if (*value)
t = asprintf(&c, "%s%.*s", *value, (int) rxed, buffer);
else
t = asprintf(&c, "%.*s", (int) rxed, buffer);
if (t == -1) return -1;
free(*value);
*value = strdup(c);
free(c);
}
// how to write to the pipe fork?
}