我有以下程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <sys/wait.h>
int main()
{
int p[2];
char *argv[2];
argv[0] = "wc";
argv[1] = "-w";
argv[2] = NULL;
pipe(p);
if (fork() == 0)
{
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
execvp(argv[0], argv);
}
else
{
close(p[0]);
write(p[1], "hello world\n", 12);
}
fprintf(stdout, "hello world\n");
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时:
$ gcc a.c
$ ./a.out
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:
hello world
$ 2
_ // the cursor is flickering here
Run Code Online (Sandbox Code Playgroud)
输入后Enter …