Pass File Descriptor - Execve (typecast)

我的梦境 提交于 2019-12-02 10:43:39

Simply casting the file descriptor to a char* isn't a good idea. It could cause data loss if the OS chooses to copy the strings and stops at the 0 bytes, so the data isn't entirely copied. It would be safer to create a string containing the file descriptor.

int pfd[2];
if(pipe(pfd) == -1)
    exitWithError("PIPE FAILED", 1);
char string1[12]; // A 32 bit number can't take more than 11 characters, + a terminating 0
snprintf(string1,12,"%i",pfd[1]); // Copy the file descriptor into a string
char *args_1[] = {"reader", argv[1], &string1[0], (char *) 0};

The reader program then uses atoi to convert this back into an int.

int fd = atoi(argv[2]);
write(fd,buf,read_test);

If you really want to use a cast, then you need to cast argv[2] as int* in your reader.

write(((int*)argv[2])[1],buf,read_test);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!