[C++] 纯文本查看 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
int main()
{
int fd, pid;
int val;
fd = open("myfile.txt", O_RDONLY);
val = fcntl(fd, F_GETFD);
fcntl(fd, F_SETFD, val|FD_CLOEXEC);
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
char chbuf[6];
bzero(chbuf, 6);
read(fd, chbuf, 5);
//fd can be used in child
printf ("child read from myfile.txt: %s\n", chbuf);
char fd2str[5];
bzero(fd2str, 5);
//call execl() function
sprintf(fd2str, "%d", fd);
int ret = execl("./myexec", "myexec", fd2str, NULL);
if (ret < 0) {
perror("execl");
exit(EXIT_FAILURE);
}
}
//in parent
waitpid(pid, NULL, 0);
close(fd);
return 0;
}
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
int main(int argc, char **argv)
{
int fd = atoi(argv[1]);
char buf[32];
bzero(buf, 32);
ssize_t bytes = read(fd, buf, 32);
if (bytes < 0) {
perror("myexec read");
exit(EXIT_FAILURE);
}
printf ("read from myfile.txt: %s\n", buf);
return 0;
}