Thread: Launch a fork every N seconds

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    13

    Launch a fork every N seconds

    Hi everyone, I have this assignment in which I need to run "ls" every N seconds. We're not allowed to use signals, we can only use the command sleep, but via an exec function, we can't use "system".

    This is the code I have:

    Code:
    main()
    {
        int N=5;
        int i;
        pid_t pid;
        pid = fork();
        if (pid==0) {
            for (i=0; i<N; i++) {
                if (fork()==0)
                    execl("/bin/ls", "ls", NULL);
            }
        }
        else if (pid>0) {
            wait(NULL);
        }
        else
            perror("fork failed");
    }
    I've tried many things, but the problem is I have to run an execl (or execvp) with sleep in it. Being mandatory, it erases the rest of the program.
    My teachers insists it can be done with execs, forks and waits. I still can't see how.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    Your attempt makes no sense. You say you want to launch ls every N seconds, but instead you launch N copies of ls.

    As for executing sleep with exec, it's pretty simple. You need to turn your N int into a string, which you can do with sprintf. Below I've called the string nstr.
    Code:
        switch (fork()) {
        case -1:
            perror("fork");
            exit(EXIT_FAILURE);
        case 0:
            execl("/bin/sleep", "sleep", nstr, (const char*)NULL);
            exit(0); // child exits
        }
        wait(NULL);  // parent waits for child
    Last edited by john.c; 12-04-2018 at 12:55 PM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 10-29-2016, 10:03 AM
  2. Replies: 5
    Last Post: 02-27-2014, 03:53 AM
  3. Convert seconds to hours, minutes and seconds
    By kkk in forum C Programming
    Replies: 2
    Last Post: 07-26-2011, 10:47 AM
  4. Launch a program
    By fighter92 in forum C++ Programming
    Replies: 1
    Last Post: 06-15-2008, 11:03 AM
  5. VS.NET launch
    By Govtcheez in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 02-08-2002, 01:13 AM

Tags for this Thread