I want to use shared memory to save characters printed by two parent-child process. the child process save ‘a’,’b’,’c’,’d’ into the first four bytes, and then the parent one save ‘A’,’B’,’C’,’D’ into the next four bytes. But it won’t work。the code is below:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
int
main(int argc, char **argv) {
int shmid,i,j,off_a,off_b;
char *ptr;
pid_t pid;
shmid = shmget(IPC_PRIVATE, 200, SHM_W | SHM_R | IPC_CREAT);
if (shmid < 0) {
printf("cannot create shared memory\n");exit(-1);
}
if ((ptr = shmat(shmid, NULL, 0)) == (void *)-1) {
printf("cannot attach shared memory to address\n");
exit(-1);
}
if ((pid = fork()) < 0) {
printf("fork error\n");exit(-1);
} else if (pid) {
wait();
for (i = 'A', off_a = 0; i <= 'D'; i++ ,off_a += 1)
sprintf(ptr + off_a,"%c",i);
printf("RESULT:%s \n", ptr);
} else {
for (j = 'a', off_b = 4; j <= 'd'; j++, off_b += 1)
sprintf(ptr + off_b,"%c",j);
exit(0);
}
}
i think the RESULT is abcdABCD, but when i run it , it print ABCD, I used gdb to debug it, and write it to a file, the ‘a’ character is lost. why this happened?
0000000 A B C D \0 b c d \0 \0 \0 \0 \0 \0 \0 \0
0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
*
The sprintf adds a trailing NULL;
Replace
with
and similarly with the other sprintf.