- 論壇徽章:
- 0
|
這個(gè)程序的用法是在主進(jìn)程中輸入命令 ,然后在子進(jìn)程中執(zhí)行命令 ,然后通過管道將輸出結(jié)果再傳回主進(jìn)程并顯示, 但是多執(zhí)行幾次命令就出現(xiàn)問題了
(這個(gè)程序還有很多問題,暫且只考慮執(zhí)行命令這個(gè)問題)
代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int fd1[2], fd2[2];
char cmdstring[128],show_buf[8192];
int n, flags;
pipe(fd1);
pipe(fd2);
pid = fork();
switch(pid)
{
case -1:
perror("fork");
exit(1);
case 0:
close(0);
close(1);
close(fd1[1]);
close(fd2[0]);
dup(fd1[0]);
dup(fd2[1]);
execl("/bin/sh","sh", NULL);
default:
close(fd1[0]);
close(fd2[1]);
flags = fcntl(fd2[0], F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd2[0], F_SETFL, flags);
while(1)
{
fgets(cmdstring, 128, stdin);
n = strlen(cmdstring);
write(fd1[1], cmdstring, n);
read(fd2[0], show_buf, 8192);
printf("%s",show_buf);
memset(show_buf, 0, 8192);
}
}
} |
|