- 论坛徽章:
- 95
|
原帖由 springzbz 于 2007-4-16 09:25 发表于 1楼
#include <sys/types.h>
#include <wait.h>
#include "errors.h"
int main( int argc, char *argv[] )
{
int status ;
char line;
int seconds;
pid_t pid; ...
因为你的提示符在父进程中打印,但是 sleep 并打印睡眠了多长时间是在子进程中,而最后的 do-while 循环(在其中调用了 waitpid) 并不会使父进程等待子进程。
试下如下的代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <wait.h>
- int
- main(void)
- {
- char line[128];
- int seconds;
- pid_t pid, pid1;
- char message[64];
- while(1){
- printf("Alarm> ");
- if(fgets(line, sizeof(line), stdin) == NULL) exit(0);
- if(strlen(line) <= 1) continue;
- if (sscanf(line, "%d %64[^\n]", &seconds, message) < 2) {
- fprintf(stderr, "Bad command\n");
- }else {
- pid1 = fork();
- if(pid1 == (pid_t)-1)
- exit(1);
- if(pid1 ==(pid_t)0) {
- sleep(seconds);
- printf("(%d) %s\n", seconds, message);
- exit(0);
- } else {
- pid = waitpid(pid1, NULL, 0);
- if (pid == (pid_t)-1){
- exit(1);
- }
- }
- }
- }
- return 0;
- }
复制代码
下面是运行的结果:
Alarm> 2 secs
(2) secs
Alarm> 3
Bad command
Alarm> 3 secs
(3) secs
Alarm> |
|