1

我想使用共享内存来保存两个父子进程打印的字符。子进程将'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);

        }
}

我认为结果是 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
*
4

1 回答 1

0

The sprintf adds a trailing NULL;

Replace

sprintf(ptr + off_a,"%c",i);

with

*(ptr + off_a) = i;

and similarly with the other sprintf.

于 2012-04-21T15:45:27.067 回答