Home  |  Buy on line  |  Contact us  |  Terms & Conditions  | 
  



New FOX Board G20



Buy on-line


FOX Board G20
FOX Board LX832
Easy Guardian
SMS FoxBox
Acme Systems srl




FOX Board LX832 is discontinued
To be informed about its availability and prices please CONTACT US
To know more about the new FOX Board G20 GO HERE

Using fork() to create a child process

The fork() function is the primitive for creating a child process that can does something in parallel with the main process

After a fork() the main process splits in two parallel process: a parent and a child processes. Both ot them see the fork() return code, but with different values: it returns 0 in the child process and the child's process ID in the parent process.

If process creation failed, fork returns a value of -1 in the parent process.

This easy example shows how to use the fork() function to create a child process that turn on the red led DL1, wait 7 seconds, turn off the led and die while the main process counts from 10 to 0 seconds:.

#include "sys/types.h"
#include "sys/wait.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "linux/gpio_syscalls.h"

int main(void) {

  int rtc;
  int sec;

  rtc=fork();

  if (rtc==0) {
    printf("Child: Fork\n");
    printf("Child: DL1 on\n");
    gpioclearbits(PORTA, PA3);
    sleep(7);
    printf("Child: DL1 off\n");
    gpiosetbits(PORTA, PA3);
    return EXIT_SUCCESS;
  }

  printf("Parent: Fork\n");
  for (sec=10;sec>0;sec--) {
    printf("Parent: %02d\n",sec);
    sleep(1);
  }
  wait(NULL);
  return EXIT_SUCCESS;
} 

Execute it

# ./fork1
Child: Fork
Child: DL1 on
Parent: Fork
Parent: 10
Parent: 09
Parent: 08
Parent: 07
Parent: 06
Parent: 05
Parent: 04
Child: DL1 off
Parent: 03
Parent: 02
Parent: 01

Related links