2012-01-28 58 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

相關問題