2012-01-28 57 views
0

我正在尝试在C中运行x分钟的程序。我需要让child进程在这段时间内进入休眠状态。任何帮助,将不胜感激。基本上我想了解fork()sleep()是如何工作的。这里是我的代码片段如何在C中运行一个程序x分钟?

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]) 
{ 
    int i = fork(); 
    printf("fork return value = %d\n", i); 
    printf("this is the time before sleep"); 
    system("date +%a%b%d-%H:%M:%S"); 
    printf("\n"); 
    if (i==0){ 
     sleep(120); 
    } 
    system("ps"); 
    printf("this is the time after sleep"); 
    system("date +%a%b%d-%H:%M:%S"); 
    printf("\n"); 
} 
+0

只是一个仅供参考 - 睡眠()不能保证,只要你问到实际入睡。它可能被信号中断。如果你真的想等一段时间,你应该检查sleep()的返回值。如果在睡眠中剩下时间,秒数会返回,您可以再次请求睡眠时间更长。 – FatalError 2012-01-28 05:38:44

回答

0
#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int main(void) 
{ 
    pid_t pid; 
    int rv=1; 

    switch(pid = fork()) { 
    case -1: 
     perror("fork"); /* something went wrong */ 
     exit(1);   /* parent exits */ 

    case 0: 
     printf(" CHILD: This is the child process!\n"); 
     printf(" CHILD: My PID is %d\n", getpid()); 
     printf(" CHILD: My parent's PID is %d\n", getppid()); 
     printf(" CHILD: I'm going to wait for 30 seconds \n"); 
     sleep(30); 
     printf(" CHILD: I'm outta here!\n"); 
     exit(rv); 

    default: 
     printf("PARENT: This is the parent process!\n"); 
     printf("PARENT: My PID is %d\n", getpid()); 
     printf("PARENT: My child's PID is %d\n", pid); 
     printf("PARENT: I'm now waiting for my child to exit()...\n"); 
     wait(&rv); 
     printf("PARENT: I'm outta here!\n"); 
    } 

    return 0; 
} 

说感谢Brian "Beej Jorgensen" Hall

+0

你的代码中的rv是什么?我看到你把它定义为int,但是我没有看到你为它赋值的地方。换句话说,我不明白什么是退出(rv)和什么等待(&rv)。 – 2012-01-29 01:11:06

+0

'rv'是孩子想要返回给父母的返回值。我没有初始化它有一些价值。现在就完成了!感谢您指出。 – 2012-01-29 04:32:28

相关问题