You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

When fork()'ing file descriptors are copied between the two new processes and will cause concurrent operations to occur on the same file. 

Non-Compliant Code Example

char c;

int pid;

int fd = open(filename,O_RDWR,0);

read(fd,&c,1);

pid = fork();

if(pid == 0)

Unknown macro: {/*child*/ read(fd,&c,1); printf("child}

else

Unknown macro: { /*parent*/ read(fd,&c,1); printf("parent}

This code's output cannot reliably be determined, and therefore should not be used.  Instead, file descriptors should not be passed through a fork() call and should be closed beforehand to prevent this error.

complient code example:

char c;

int pid;

int fd = open(filename,O_RDWR,0);

read(fd,&c,1);

close(fd);

pid = fork();

if(pid == 0)

Unknown macro: {/*child*/ fd = open(filename,O_RDONLY,0); read(fd,&c,1); read(fd,&c,1); printf("child}

else

Unknown macro: { /*parent*/ fd = open(filename,O_RDWR,0); read(fd,&c,1); read(fd,&c,1); printf("parent}
  • No labels