c waitpid code example

Example 1: c waitpid

#include <sys/types.h>
#include <sys/wait.h>

pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);

Example 2: example code of waitpid

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>

int main(){
	int pid;
    int status;
    pid =fork();
    if(pid<0){
        printf("Error");
    }
    else if(pid==0){
         // Child Process
         for(int i=0;i<100;i++){
            value-=1;
            printf("%d \n",value);
         }
        exit(EXIT_SUCCESS);
    }
	
   waitpid(pid,&status,0); // WAIT till child gets over
	// Parent process
   for(int i=0;i<100;i++){
            value-=1;
            printf("%d \n",value);
         }
   printingFunction();
    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
    return 0;
    
	}
}

Example 3: C delay

/** really not much to say...
   just a way to program a delay
   between commands in your code. **/

//C library statement
#include <time.h>

//Driver program
void dealy(int numOfSec)
{
	/* the delay itself runs with milli seconds
	   so here we multiply the seconds by 1000.  */
	int numOfMilliSec = 1000 * numOfSec;
	
	/* Making the time pass with nothing running
	   until the time is up.                     */
	time_t startTime = clock();
	while(clock() < startTime + numOfMilliSec);
}

/*To use the delay just use the command:
  delay(x);
  you need to replace x with the number
  of seconds that you want the delay to
  be.                                    */
  
///The code itself without the details:

#include <time.h>

void delay(int numOfSec)
{
	int numOfMilliSec = 1000 * numOfSec;
	time_t startTime = clock();
	while(clock() < startTime + numOfMilliSec);
}

Tags:

C Example