我想要使用共享内存将getaddrinfo结构(* res)的输出传递给父进程(从子进程),如下所示
pid = fork(); if (pid == 0) { ..... iStatus = getaddrinfo(argv[1], NULL, &hints, &servinfoC); ... shmid = shmget(GETADDR_SHM_KEY, SHMSZ, IPC_CREAT | 0666); .... shmC = shmat(shmid, (void*)NULL, 0)); memcpy(shmC, servinfoC, sizeof(struct addrinfo)); freeaddrinfo (servinfoC); } else { struct addrinfo *servinfoP; while ((pid = waitpid (pid, &status, WUNTRACED | WCONTINUED)) > 0) shmid = shmget(GETADDR_SHM_KEY, SHMSZ, 0666 | IPC_CREAT); shmP = shmat(shmid, (void*)NULL, 0)); /*HELP Copy shmP to servinfoP struct*/ }我尝试了memcpy,但它没有帮助,因为addrinfo需要内存分配。
提前感谢您的时间和帮助
问候Manoj
I wanted to pass output of getaddrinfo structure (*res) into parent (from child) process using shared memory as below
pid = fork(); if (pid == 0) { ..... iStatus = getaddrinfo(argv[1], NULL, &hints, &servinfoC); ... shmid = shmget(GETADDR_SHM_KEY, SHMSZ, IPC_CREAT | 0666); .... shmC = shmat(shmid, (void*)NULL, 0)); memcpy(shmC, servinfoC, sizeof(struct addrinfo)); freeaddrinfo (servinfoC); } else { struct addrinfo *servinfoP; while ((pid = waitpid (pid, &status, WUNTRACED | WCONTINUED)) > 0) shmid = shmget(GETADDR_SHM_KEY, SHMSZ, 0666 | IPC_CREAT); shmP = shmat(shmid, (void*)NULL, 0)); /*HELP Copy shmP to servinfoP struct*/ }I tried memcpy but it didnt helped because of memory allocation required for addrinfo.
Thank you in advance for your time and help
Regards Manoj
最满意答案
这听起来像你试图用fork / processes实现异步DNS查找,这真的是一个非常糟糕的主意。 如果你不想要一个异步DNS库,只需要使用线程而不是fork 。 然后生成的struct addrinfo已经存在于程序的地址空间中,并且调用者可以使用(并释放)它。
新线程应该调用getaddrinfo并在调用者完成时通知它; 你用来通知调用者的方法应该取决于你的程序的事件处理是如何工作的。 假设它是单线程的,你可能使用select / poll (或像libevent这样的抽象),因此线程可以使用select的管道来指示查询何时完成。
PS除了传统接口(如X11)之外,不要使用shmget等。 使用MAP_SHARED|MAP_ANONYMOUS (对于只与您的fork子项共享的匿名共享内存)或shm_open (POSIX命名的共享内存)或者甚至是普通文件的mmap ,有许多更清晰更现代的方式来执行共享内存。 。
It sounds to me like you're trying to implement asynchronous DNS lookups with fork/processes, which is a really really bad idea. If you don't want an async DNS library, just use threads instead of fork. Then the resulting struct addrinfo is already in your program's address space and it can be used (and freed) by the caller.
The new thread should call getaddrinfo and inform the caller when it finishes; the method you use to inform the caller should depend on how your program's event handling works. Assuming it's single-threaded, you're probably using select/poll (or an abstraction thereof like libevent) so it may make sense for the thread to use a pipe that you can select on to indicate when the lookup is done.
P.S. Never use shmget etc. except for legacy interfaces (like X11) that require it. There are much cleaner more modern ways to do shared memory like mmap with MAP_SHARED|MAP_ANONYMOUS (for anonymous shared memory that you'll only share with your forked children) or shm_open (POSIX named shared memory) or even mmap of ordinary files...
更多推荐
发布评论