I’ve been at this for a while and I’m not sure why I keep getting the bad file descriptor error, I imagine it’s maybe related to the clone() function, and how I’m trying to pass the pipe as an argument, but I’m not sure, I’ve tried looking it up online, but still haven’t found an answer for this yet. I did try using signals still wasn’t able to make it work.
#define _GNU_SOURCE
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sched.h>
#include <stdio.h>
#include <unistd.h>
// 64kB stack
#define FIBER_STACK (1024*64)
int threadFunction(void* argument)
{
int pipefd = *((int*)argument);
char* info = "INFO!n";
if (write(pipefd, info, 10) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
printf("Child thread exitingn");
return 0;
}
int main()
{
void* stack;
pid_t pid;
int pipefd[2];
if (pipe(pipefd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
// Allocate the stack
stack = malloc(FIBER_STACK);
if (stack == 0)
{
perror("malloc: could not allocate stack");
exit(EXIT_FAILURE);
}
printf("Creating child threadn");
// Call the clone system call to create the child thread
pid = clone(&threadFunction, (char*)stack + FIBER_STACK,
SIGCHLD | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM,(void*)&pipefd[1]);
if (pid == -1)
{
perror("clone");
exit(EXIT_FAILURE);
}
close(pipefd[1]);
char buffer[1024];
/* read pipe */
read(pipefd[0], buffer, 5);
printf("%s n", buffer);
pid = waitpid(pid, 0, 0);
if (pid == -1)
{
perror("waitpid");
exit(EXIT_FAILURE);
}
free(stack);
printf("Child thread returned and stack freed.n");
return 0;
}
In theory, the code should be able to run the write() function, but I just keep getting the bad file descriptor error, I really don’t know what I’m missing here, doesn’t help that I’m totally new to the concept of pipes.
Guilherme Garcia Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.