- 论坛徽章:
- 0
|
这只是一个测试程序,所要实现的也只是输入“ls|wc”(格式:没有空格)能够正常显示就好了,但是问题是貌似管道根本没连起来,而我已经找了一下午错误了,无果,望各位高手相助~
其中的一些printf是为了调试,不需要的可以删去~
#include <sys/wait.h> /* waitpid() require it */
#include <stdio.h>
#include <string.h>
#include <stdlib.h> /* exit() require it */
#include "unistd.h" /* fork(),execlp() require it */
#define MAXLINE 4096
int main(void){
char buffer[MAXLINE];
pid_t pid1;
pid_t pid2;
int status;
char *command;
char *command1;
char *command2;
int fd[2];
printf("%%");
int len;
while(fgets(buffer,MAXLINE,stdin) != NULL){
if(buffer[strlen(buffer) - 1] == '\n')
buffer[strlen(buffer) - 1] = 0;
command1 = strtok(buffer, "|");
if((command2=strtok(NULL, "|")) != NULL){
pipe(&fd[0]);
len = strlen(command1); //add '\0' to the end of command1
command = malloc(len+1);
strncpy(command, command1, len);
command[len] = '\0';
command1 = command;
len = strlen(command2); //add '\0' to the end of command2
command = malloc(len+1);
strncpy(command, command2, len);
command[len] = '\0';
command2 = command;
printf("command1:%s\n",command1);
printf("command2:%s\n",command2);
if((pid1=fork()) != 0){ //fork
printf("pid1@aaa:%d\n",pid1);
waitpid(-1, &status, 0);
printf("after waitpid\n");
}
else{
printf("pid1:%d\n",pid1);
if((pid2=fork()) != 0){ //fork
sleep(2);
printf("pid1@bbb:%d\n",pid1);
printf("pid2@bbb:%d\n",pid2);
close(fd[1]);
close(0);
printf("in\n");
// printf("pid2");
dup(fd[0]);
printf("after dup2\n");
close(fd[0]);
printf("after close(fd[0])\n");
execlp(command2,command2,(char *)0);
printf("after execlp\n");
}
else{
close(fd[0]);
printf("pid1@ccc:%d\n",pid1);
printf("pid2@ccc:%d\n",pid2);
close(1);
dup(fd[1]);
close(fd[1]);
execlp(command1,command1,(char *)0);
sleep(1);
}
}
}
else {
if((pid1 = fork()) < 0){
printf("fork error\n");
}else if(pid1 == 0){
execlp(buffer, buffer, (char *)0);
printf("couldn't execute: %s\n", buffer);
exit(127);
}
if((pid1 = waitpid(pid1, &status, 0)) < 0)
printf("waitpid error\n");
printf("%%");
}
}
exit(0);
}
[ 本帖最后由 teloon 于 2009-4-2 18:26 编辑 ] |
|