Java7
C Programming
Spawn multiple child processes from the same parent
May 22nd
Forking multiple child processes is as simple as putting a loop over pid_t pid = fork(), but forking multiple needs an extra step forward. Seeing this question often asked in the forums, as i also did initially when trying to find an answer, heres how.
Forking multiple child processes from the same parent ancestor
#include <stdio.h>
#include <error.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int child = 5; // create 5 child
int i; // iterator
for(i = 0; i < child; i++)
{
pid = fork(); // fork a child
if (pid > 0) // parent
{
wait( (int*)0 ); // pass in null pointer because we're not interested with the status
}
if(pid == 0) // child
{
printf("Child %i running ... pid is %d ... ppid is %d ... \n", i, getpid(), getppid());
exit(0);
}
if(pid < 0){ // error forking
perror("fork call");
printf("fork error");
exit(1);
}
}
exit(0);
}
Results
The parent (ppid) remains the same for each child process spawned.
Have fun playing around with the position of the fork() system call to see different results!
C Programming File Operations (Open) Recipe
Apr 16th
Opening a file for read only access
// open a file for read only
int fd = open("sample", O_RDONLY);
Opening a file for write only access
// open a file for write only
int fd2 = open("sample", O_WRONLY);
Opening a file for read and write access
// open a file for read and write access
int fd3 = open("sample", O_RDWR);
Opening a file, and create if it does not exist.
// open a file, create one if not found
int fd4 = open("sample2", O_CREAT, 0766);
The full program (with all above file operations)
#include <stdio.h>
#include <fcntl.h>
int main()
{
// open a file for read only
int fd = open("sample", O_RDONLY);
// close file
close(fd);
// open a file for write only
int fd2 = open("sample", O_WRONLY);
// close file
close(fd2);
// open a file for read and write access
int fd3 = open("sample", O_RDWR);
// close file
close(fd3);
// open a file for read and write access
int fd4 = open("sample2", O_CREAT, 0766);
// close file
close(fd4);
}
Reference
http://en.wikipedia.org/wiki/Fcntl.h
