shell用fork建立新进程,用exex在新进程中运行用户指定的程序,最后shell用wait命令等待新进程结束。wait系统调用同时从内核取得退出状态或者信号序号以告知子进程是如何结束的。
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<sys/wait.h>
5 #include<sys/types.h>
6 int main()
7 {
8 printf("[g33@localhost myShell]$");
9 fflush(stdout);
10 sleep(5);
11 char cmd[128];
12 ssize_t s = read(0,cmd,sizeof(cmd)-1);
13 // cmd[s-1]='\0';
14 if(s>0)
15 {
16 cmd[s-1]='\0';
17 }
18 else
19 {
20 perror("read");
21 return 1;
22 }
23 printf("%s\n",cmd);
24
25 char *_argv[32];
26 _argv[0]=cmd;
27 char *start = cmd;
28 int i = 1;
29 while(*start)
30 {
31 if(isspace(*start))
32 {
33 *start = '\0';
34 start++;
35 _argv[i] = start;
36 i++;
37 continue;
38 }
39 start++;
40 }
41 _argv[i]=NULL;
42 pid_t id = fork();
43 if(id<0)
44 {
45 perror("fork");
46 }
47 else if(id==0)
48 {//child
49
50 execvp(_argv[0],_argv);
51 exit(2);
52 }
53 else
54 {//father
55 int status = 0;
56 pid_t ret = waitpid(id,&status,0);
57 if(ret>0&&WIFEXITED(status))
58 {
59 printf("wait success...exit code:%d\n",WEXITSTATUS(status));
60 }
61 else
62 {
63 printf("wait filed..\n");
64 return 3;
65 }
66 }
67
68 return 0;
69 }
70