CLONE_FILES example
This post we will write a code, which will give us an observation what changes when CLONE_FILES is added and when it is removed.
Code:
Output:
Notes:
1. You can see from the code when we passed CLONE_FILES, when the child close file descriptor, it was closed in the parent process file descriptor too.
2. So, any operations which are performed on file descriptor (read, write, fcntl) by one process will affect the other process too
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _GNU_SOURCE | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <fcntl.h> | |
#include <sched.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
#define STACK_SIZE 65536 | |
int fd; | |
static int child_func(void *arg) | |
{ | |
close(fd); | |
return 0; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
//Allocate stack for child task | |
char *stack = malloc(STACK_SIZE); | |
unsigned long flags = 0; | |
char buf[256]; | |
int status; | |
fd = open("file.txt", O_RDWR); | |
if (fd == -1) { | |
perror("Failed to open file\n"); | |
exit(1); | |
} | |
if (!stack) { | |
perror("Failed to allocate memory\n"); | |
exit(1); | |
} | |
if (argc == 2 && !strcmp(argv[1], "files")) | |
flags |= CLONE_FILES; | |
if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, NULL) == -1) { | |
perror("clone"); | |
exit(1); | |
} | |
if (wait(&status) == -1) { | |
perror("Wait"); | |
exit(1); | |
} | |
printf("Child exited with status:%d\n", status); | |
status = read(fd, buf, 100); | |
if (status < 0) { | |
perror("Read Failed\n"); | |
exit(1); | |
} | |
printf("Parent read:%s\n", buf); | |
close(fd); | |
return 0; | |
} |
Output:
Notes:
1. You can see from the code when we passed CLONE_FILES, when the child close file descriptor, it was closed in the parent process file descriptor too.
2. So, any operations which are performed on file descriptor (read, write, fcntl) by one process will affect the other process too
Comments
Post a Comment