LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 845|回复: 5

请问这个 程序怎么能改正错误?

[复制链接]
发表于 2004-1-24 22:57:38 | 显示全部楼层 |阅读模式
这个程序的要求是打印出进程推出时的状态。

  1. #include <sys/types.h>
  2. #include <sys/wait.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. static void pr_exit(int);
  6. int
  7. main(void)
  8. {
  9.     pid_t pid;
  10.     int   *status;
  11.     if((pid=fork())<0) {     /* fork一个子进程 */
  12.            printf("fork error\n");
  13.            exit(-1);
  14.      }
  15.      else if (pid ==0 ) {    /* child process */
  16.              sleep(2);
  17.              if( (waitpid(pid,&status,0)) != pid ) {  /* 把进程的信息贮存在status*/
  18.                      printf("waitpid error\n");
  19.                      exit(-1);
  20.              }
  21.              exit(0);  /* KILL 子程序 */
  22.              pr_exit(status);  /* 分析status */
  23.       }
  24.       exit(0);
  25. }

  26. static void
  27. pr_exit(int status)  /* 这个函数的作用是分析status */
  28. {
  29.       int status;
  30.       if(WIFEXITED(status))
  31.               printf("exit status = %d\n",WEXITSTATUS(status));
  32.       else if(WIFSIGNALED(status))
  33.               printf("exit status = %d%s\n",WTERMSIG(status),
  34. #ifdef WCOREDUMP
  35.               WCOREDUMP(status) ? "(core file generated)" : "" );
  36. #else
  37.        "");
  38. #endif
  39.        else (WIFSTOPED(status))
  40.                printf("child stopped ,signal number = %d\n",
  41.                        WSTOPSIG(status));
  42. }

  43. # gcc -c wait.wen.c
  44. wait.wen.c: In function `main':
  45. wait.wen.c:17: warning: passing arg 2 of `waitpid' from incompatible pointer type
  46. wait.wen.c:22: warning: passing arg 1 of `pr_exit' makes integer from pointer without a cast
  47. wait.wen.c: In function `pr_exit':
  48. wait.wen.c:30: warning: declaration of `status' shadows a parameter
  49. wait.wen.c:41: parse error before "printf"
复制代码

发表于 2004-1-24 23:21:42 | 显示全部楼层
不知道是devel兄是贴代码的时候出错了呢,还是鄙人才疏学浅,不知道C语言还可以这样写,我实在是看不明白啊。能把你的代码整理一下么?
 楼主| 发表于 2004-1-25 00:27:36 | 显示全部楼层
不好意思,没说清楚。。可能算法也错了。请指教!!!
发表于 2004-1-25 15:48:20 | 显示全部楼层
呵呵,看看你的status吧!

在main中的定义是 int * status
而在 pr_exit(int status)
发表于 2004-1-25 20:10:34 | 显示全部楼层
把main里的int *status;改成int status;
把pr_exit里的int status;删掉
另外,waitpid应该是在父进程里调用的,你的写到子进程里了

pr_exit里的printf错误我还没看出来
发表于 2004-1-25 20:12:41 | 显示全部楼层
else (WIFSTOPED(status))
少一个if,少一个'P',改成
else if(WIFSTOPPED(status))
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表