Reputation: 23
i have to make program, which will make two children processes. These processes will write something(string...) in file. Parent process should decide which process is going to write to file i have created children processes, but i am stuck at these signals and i don't have a clue how to do this
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#define READY_SIGNAL SIGUSR1
#define max 1000
int main(int argc, char *argv[]) {
FILE *file;
int o;
char *name;
opterr = 0;
while ((o = getopt(argc, argv, "hp:")) != -1)
switch (o) {
case 'h':
Help();
exit(1);
default:
exit(1);
}
argc -= optind;
argv += optind;
if(argc==0){
printf("file name\n");
scanf("%s",&name);
file=fopen(name,"a+");
if( file != NULL)
{
printf("file created\n");
// fclose(file);
}
else printf("the file does not exist\n");
}
else if(argc>1) {
return(1);
}
else
meno=argv[0];
file=fopen(name,"a");
if( file != NULL){
printf("file created\n");
}
else printf("the file does not exist\n");
pid_t child_pid, child_pid2;
printf ("the main program process ID is %d\n", (int) getpid());
child_pid = fork () ;
if (child_pid != 0) {
printf ("this is the parent process, with id %d\n", (int) getpid ());
printf ("the child's process ID is %d\n",(int) child_pid );
}
else {
printf ("this is the child process, with id %d\n", (int) getpid ());
exit(0);
}
child_pid2 = fork () ;
if (child_pid2 != 0) {
printf ("this is the parent process, with id %d\n", (int) getpid ());
printf ("the child's process ID is %d\n",(int) child_pid2 );
}
else
{
printf ("this is the child process, with id %d\n", (int) getpid ());
exit(0);
}
return 0;
}
thanks
Upvotes: 0
Views: 2887
Reputation: 4314
To start with your child processes are exiting as soon as they are created. If they didn't then the first child would then create a child of it's own. You probably want to create the children in a for loop and do something like:
if(child_pid[i] != 0)
{
/* This is the parent. */
}
else
{
/* This is the child. */
do_child_stuff();
exit(0);
}
It is a bad idea to open the file before you fork(). You will end up with three processes who all hold a file handle to the same file with the same permissions. Life starts getting complicated if you do that! In general only open files when you really need to, and close them as soon as you have finished using them.
I think what your question means is that you want the parent process to tell the child to write by sending a signal from the parent to the child. There are easier ways of doing this, but I guess your teacher wants you to demonstrate how to do it with signals.
First off, you need to write a signal handler. See http://linux.die.net/man/2/signal for more information on how to do this.
Second you need to actually send the signal. See http://linux.die.net/man/2/kill for more information. Note that the name "kill" is a bit of a misnomer.
Upvotes: 2