【发布时间】:2020-03-21 09:34:24
【问题描述】:
我有以下程序:
#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");
}
当我运行它时:
$ gcc a.c
$ ./a.out
我得到了以下信息:
hello world
$ 2
_ // the cursor is flickering here
在我输入Enter 后,程序退出。这是什么原因?另外,如果我这样交换父进程和子进程中的内容:
#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(p[0]);
write(p[1], "hello world\n", 12);
}
else
{
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
execvp(argv[0], argv);
}
fprintf(stdout, "hello world\n");
}
我得到了预期的输出:
hello world
2
$
程序已退出并准备好获取下一个命令。第一个程序有什么问题?
【问题讨论】:
-
一方面,你的
char *argv[2]需要是argv[3]来保存你想要加上终止NULL指针的两个参数。 -
后台
wc的输出在提示后打印。您的 shell 正在等待您输入命令,例如,在打印出2后立即输入ps并查看正在运行的进程。 -
@JonathanLeffler 是的,这是真的。那个时候程序已经退出了。
wc的输出出现在提示符之后。