我想使用共享内存来保存由两个父子进程打印的字符。子进程将'a','b','c','d'保存到前四个字节中,然后父进程将'A','B','C','D'保存到接下来的四个字节中字节。但它不起作用。代码如下:
#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);
}
}
我认为RESULT是abcdABCD,但是当我运行它时,它打印ABCD,我使用gdb来调试它,并将其写入文件,'a'字符丢失。为什么会这样?
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
*
答案 0 :(得分:0)
sprintf添加一个尾随的NULL;
替换
sprintf(ptr + off_a,"%c",i);
与
*(ptr + off_a) = i;
与其他sprintf类似。