如何在C中运行程序x分钟?

时间:2012-01-28 04:58:50

标签: c system fork sleep

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

#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");
}

1 个答案:

答案 0 :(得分: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