Reputation: 390
I'm trying to make a program that calculates the prime factors of a number (x for exemple) using fork()
In the child proces I want to iterate form 2 to x/2-1 and see witch number divides x. But i don't know how to let the parent proces to know that I modified a variable inside the child porces
And now my question is.. how do i sent information for child to parent?
int main(int argc, char *argv[]){
int var = 0;
pid = fork();
if(pid > 0){
if(var = 0){
var++;
else{do nothing}
else if(pid == 0){
printf("%d\n", var); here the program will print 0 but i want it to print 1. How?
}
}
}
}
Upvotes: 0
Views: 74
Reputation: 16540
the following proposed code:
int main( void )
so no warning messages from the compiler about unused parameterscase 0:
and default
code blocks so can have local variables within those code blocksand now, the proposed code:
#include <stdio.h> // printf(), perror()
#include <sys/types.h>// pid_t
#include <unistd.h> // fork(), pipe(), read()
#include <sys/wait.h> // wait()
#include <stdlib.h> // exit(), EXIT_SUCCESS, EXIT_FAILURE
enum { READ_FROM, WRITE_TO };
int main( void )
{
int status;
int fd[2];
if( pipe( fd ) )
{
perror( "pipe failed" );
exit( EXIT_FAILURE );
}
pid_t pid = fork();
switch( pid )
{
case -1:
perror( "fork failed" );
exit( EXIT_FAILURE );
case 0: // child process
{
int var = 1;
ssize_t bytesWritten;
close( fd[ READ_FROM ] );
if( ( bytesWritten = write( fd[ WRITE_TO ], &var, sizeof( var ) ) ) != sizeof( int ) )
{
perror( "write failed" );
close( fd[ WRITE_TO ] );
exit( EXIT_FAILURE );
}
close( fd[ WRITE_TO ] );
exit( EXIT_SUCCESS );
}
default: // parent process
{
int buffer = 0;
ssize_t bytesRead;
close( fd[ WRITE_TO ] );
if( ( bytesRead = read( fd[ READ_FROM ], &buffer, sizeof( buffer ) ) ) != sizeof( int ) )
{
perror( "read failed" );
close( fd[ READ_FROM ] );
wait( &status ); // waits for child to exit
exit( EXIT_FAILURE );
}
printf( "%d\n", buffer );
close( fd[ READ_FROM ] );
wait( &status ); // waits for child to exit
break;
}
}
}
A typical/successful run of the program results in
1
Upvotes: 1