I have one command (cmd_c
) which can get input from STDIN and process the input data.
I want to call this command in a process A
, and process A
will provide data to the cmd_c
.
The process A
called fork()
+ execv()
to start a child process to run command of cmd_c
, but I did NOT find the right way to send data from process A
to cmd_c
?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
int pid;
/* continued */
if ((pid = fork()) > 0) {
/// does something else
/// How to send data to child process's STDIN???
wait(NULL);
} else {
char *arg_list[] = {"./cmd_c", NULL};
int rc = execv("./cmd_c", arg_list);
printf("Child execv = %d\n", rc);
}
return 0;
}
The cmd_c.c
is as follows,
#include <stdio.h>
int main()
{
char buf[256];
while (fgets(buf, sizeof(buf) - 1, stdin)) {
printf("XXXXXXXXX %s\n", buf);
}
return 0;
}
Thanks.
Create a pipe and the two fds connected to the read and write ends with pipe()
, juggle them to the correct places in the child (and parent if needed) with dup2()
, and then read and write using the fds. If you're going to exec()
another program, you need to move the read end to the stdin fd (0) in the child, but the parent can keep its own stdout separate from the pipe write fd if it runs your code.
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
/* [0] = read end, [1] = write end */
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == 0) {
/* child, move the read end to stdin and close the orig pipe fds */
close(STDIN_FILENO);
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execlp("sed", "sed", "s/.*/sed((&))/", (char *) NULL);
} else {
/* parent, close the read end */
close(pipefd[0]);
write(STDOUT_FILENO, "hello\n", 6); /* directly to stdout */
write(pipefd[1], "world\n", 6); /* written to the pipe */
/* close the write end when done, so the child exits */
close(pipefd[1]);
wait(NULL);
}
}
The output should be:
hello
sed((world))
(But note that writes through the pipe and child will be slower to reach the terminal (or where ever stdout is connected), so you may get some reordering of the output. Doesn't matter if you don't write directly to stdout from the parent.)