Write a small program sleepy that gets a loop count from the

Write a small program, sleepy, that gets a loop count from the command line:

sleepy n

where n is the number of seconds for which the program should run. Implement this timing by putting a loop n times of sleep(1) - this will put the program to sleep for one second n times before exiting.

In each loop print out the process ID and the loop count so that that particular process can be identified.

The process ID can be obtained from the getpid function:

#include <sys/types.h>
#include <unistd.h>
...
pid_t getpid(void);

This function returns the process ID of the calling process.

This is what I\'ve done:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <ctype.h>

int main(int argc, char* argv[])

{
   int seconds;
   int i;
if(isdigit(argv[i][0])){
seconds = atoi(argv[i]);
printf(\"seconds = %d\ \", seconds);
}
   int pid = (int) getpid();
   int i;
       for (i = 0; i<seconds; ++i){
           sleep(1);
           printf(\"cycle %d, pid = %d\ \", i, pid);
          
          
       }
  
return 0;
}

#include <sys/types.h>
#include <unistd.h>
...
pid_t getpid(void);

This function returns the process ID of the calling process.

Solution

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
int seconds;
int i;
  
seconds = atoi(argv[1]);
printf(\"seconds = %d\ \", seconds);
  
int pid = (int) getpid();

for (i = 0; i<seconds; ++i){
sleep(1);
printf(\"cycle %d, pid = %d\ \", i, pid);
  
  
}
  
return 0;
}

================================================

Output:

akshay@akshay-Inspiron-3537:~/Chegg$ gcc sleep.c
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out 2
seconds = 2
cycle 0, pid = 2956
cycle 1, pid = 2956

Write a small program, sleepy, that gets a loop count from the command line: sleepy n where n is the number of seconds for which the program should run. Impleme
Write a small program, sleepy, that gets a loop count from the command line: sleepy n where n is the number of seconds for which the program should run. Impleme

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site