Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

fork()-kutsun jälkeen ei voi olla varma siitä kumpi prosessi (äiti vai lapsi) jatkaa aiemmin suoritustaan. Jos järjestys tärkeää, on ohjelmoitava itse synkronointi
Esim 1.

Code Block
#include < sys/types.h >
#include < unistd.h >
int glob = 6; /\* external variable in initialized data \*/
char buf\[\] = "a write to stdout\n";
int
main(void)
< 0)perror("fork error");else if (pid == 0){ /* child */ glob++; /* modify variables */ var++; " >{ {
int var; /\* automatic variable on the stack \*/ 
pid_t pid; 


var = 88; 
if (write(STDOUT_FILENO, buf, sizeof(buf)-1) \!= sizeof(buf)-1) 
perror("write error"); 
printf("before fork\n"); /\* we don't flush stdout \*/ 


if ( (pid = fork()) < 0) 
perror("fork error"); 
else if (pid == 0) 
{ /\* child \*/ glob++; /\* modify variables \*/ var++; }
else
sleep(2); /\* parent \*/


printf("pid=%d,glob=%d,var=%d\n",getpid(), glob, var);
exit(0);
}


Lapsiprosessi luodaan, kun:

...