【发布时间】:2012-11-29 21:32:08
【问题描述】:
我正在编写一个运行 Linux 命令的 C 程序,例如:
$ cat /etc/passwd |切-f1 -d:|排序
这个想法是使用 fork() 创建子进程以使用 execlp() 运行命令。我计划使用两个管道进行通信并使用 dup() 引导输入输出。
输出错误:
ls -l | wc -c on 命令返回 1746 程序返回 1761
代码(编辑以反映建议):
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
int main()
{
int i,fd1[2],status,listpid[2];
pid_t child;
pipe(fd1);
for(i=0; i< 2; i++)
{
printf("\ncreating child\n");
if((child = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(child == 0)
{
if(i == 0)
{
close(1); dup(fd1[1]);
close(fd1[0]);
close(fd1[1]);
printf("\nrunning ls -l\n");
fflush(stdout);
execlp("ls","ls","-l", (char *)NULL);
exit(EXIT_SUCCESS);
}
else if(i == 1)
{
close(0); dup(fd1[0]);
close(fd1[1]);
close(fd1[0]);
printf("\nrunning wc -c\n");
fflush(stdout);
execlp("wc","wc","-c", (char *)NULL);
exit(EXIT_SUCCESS);
}
}
else
{
listpid[i]=child;
}
}
close(fd1[0]);
close(fd1[1]);
for(i = 0; i < 2; i++)
{
waitpid(listpid[i], &status, 0);
if(WIFEXITED(status))
{
printf("\n[%d] TERMINATED (Status: %d)\n",listpid[i], WEXITSTATUS(status));
}
}
exit(EXIT_SUCCESS);
}
【问题讨论】:
-
参见stackoverflow.com/questions/13438643/… 以使用
NULL作为最后一个参数。 -
将
\n放在printf的末尾是传统的做法,如果它是终端,这也避免了必须刷新stdout。
标签: c linux for-loop exec fork