Arthur
Arthur

Reputation: 21

Input command with system() and sleep()

Is there a way to use system() and ask for the code to wait a few seconds?

I have been trying something like:

system("MyCmd");
sleep(8000);

However, sleep() terminates "MyCmd" execution.

Any thoughts?

Upvotes: 2

Views: 56

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

However, sleep() terminates "MyCmd" execution.

No. The sleep() expression doesn't terminate the child process created with the system() call, the expressions

system("MyCmd");
sleep(8000);

will just be executed sequentially.


What you can do is to call fork() to create a child process, call sleep() in the parent process, and kill() the child process, if it's still running after the parent process awakes:

pid_t pid = fork();

if (pid == 0) {
    // child process
    execl ("/bin/MyCmd", "MyCmd", (char *)0);
}
else if (pid > 0) {
    // parent process
    sleep(8000);
    kill(pid,SIGKILL);
}
else {
    // fork failed
    printf("fork() failed!\n");
    return 1;
}

Upvotes: 1

Related Questions