Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

ID: 3789468 • Letter: W

Question

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.

Explanation / Answer

#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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote