1、实验代码
dup.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main1 (void)
{
int fd, new_fd;
fd = open ("write.txt", O_RDWR | O_CREAT, 0644);
if (fd == -1)
{
perror ("open");
exit (EXIT_FAILURE);
}
new_fd = dup (fd);
printf ("fd = %d\nnew_fd = %d\n", fd, new_fd);
write (fd, "hello", strlen("hello"));
close (fd);
write (new_fd, "world", strlen("world"));
close (new_fd);
return 0;
}
int main (void)
{
int new_fd;
new_fd = dup (1);
write (1, "hello", strlen("hello"));
write (new_fd, "world\n", strlen("world\n"));
close (new_fd);
return 0;
}
```css
dup2.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define handler_error(msg) \
{perror(msg);exit(EXIT_FAILURE);}
int main (void)
{
int fd, new_fd;
char *buf = "hello world\n";
fd = open ("data.log", O_RDWR | O_CREAT, 0644);
if (fd == -1)
handler_error("open");
new_fd = dup2 (fd, 1);
if (new_fd == -1)
handler_error("dup2");
printf ("fd: %d\n new_fd: %d\n", fd, new_fd);
write (1, buf, strlen(buf));
close (fd);
return 0;
}
pipe-dup.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (void)
{
int pipe_fd[2];
if (pipe (pipe_fd) == -1)
{
perror ("pipe");
exit (EXIT_FAILURE);
}
else
{
int ret_from_fork;
ret_from_fork = fork ();
if (ret_from_fork == 0) // child process
{
// close (1);
dup2 (pipe_fd[1], 1);
execlp ("cat", "cat", "dup.c", NULL);
}
else
{
// close (0);
dup2 (pipe_fd[0], 0);
close (pipe_fd[1]);
execlp ("grep", "grep", "include", NULL);
}
}
return 0;
}
2、执行结果