Sons of the process of

Category: Linux/Unix Community -> Applications Author: m4ker Date: 2010-09-21 14:49:41
 
m4ker
2010-09-21 14:49:41
# Include <stdio.h>
# include <unistd.h>
# include <fcntl.h>
# include <stdlib.h>
# include <string.h>
# include <strings.h>

int main ()
{
int fd = open ("a.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fork () == 0) {
char c = 'A';
for (; c <= 'Z'; c + +) {
write (fd, & c, 1);
sleep (1);
}
close (fd);
exit (0);
}
int i = 0;
char str [10] = {};
for (; i <26; i + +) {
bzero (str, sizeof (str)) ;/ / memset (str, 0, sizeof (str));
sprintf (str, "% d", i);
write (fd, str, strlen (str)) ;/ / I want to know why it is printed A01B2C3D ... Do not interactive ..
print it?
sleep (1);
}
close (fd);
}
cfy_leon0207
2010-09-21 14:55:07
interactive fine.
linjiayu09
2010-09-21 15:10:36
here is not guaranteed parent and child processes interact to write files, sleep can not control, if we must achieve cross print requirements (A0B1C2D3 this), you need to be synchronized between parent and child.
cfy_willon
2010-09-21 15:26:14
Sons displacement processes use the same file it
ziyuan_8045
2010-09-21 15:37:46
landlord wants 1 on 1 interval can be socketpair, the parent process to write a second file to write one byte and the parent process only read one byte to perform the next loop. subprocess read byte to pipe a write once, and finished to give the parent process writes a byte.
qq7238864
2010-09-21 15:51:08
Landlord program prints the result is random, it can not be guaranteed to be interactive print
ivy036
2010-09-21 15:53:32
sleep can not be used for process synchronization, because it does not guarantee that woke up after another process has been scheduled.
can use other methods of synchronization between processes, such as signal, pipes, semaphores, message queues, and so on.
zzs3339
2010-09-21 15:58:57
you have done is not guaranteed parent and child interactive execution, this is random, if you want to achieve then use the thread / process synchronization mechanism
pcmail
2010-09-21 16:08:42
interprocess use semaphores to synchronize. semget () creates a semaphore. semop () operation on the semaphore.