Child process cannot get the input from stdin written by parent process - linux

In child process, I use execl() to execute a program "test1" with the input from stdin. However, the input from stdin cannot be passed to "test1", but it is fine for "sort" command.
example.c
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int fds[2]; // an array that will hold two file descriptors
pipe(fds); // populates fds with two file descriptors
pid_t pid = fork(); // create child process that is a clone of the parent
if (pid == 0) { // if pid == 0, then this is the child process
dup2(fds[0], STDIN_FILENO); // fds[0] (the read end of pipe) donates its data to file descriptor 0
close(fds[0]); // file descriptor no longer needed in child since stdin is a copy
close(fds[1]); // file descriptor unused in child
//if (execl("/usr/bin/sort", "sort", (char *)0) < 0) exit(0);//working
if (execl("./test1", "test1", (char *)0) < 0) exit(0);//not working
}
// if we reach here, we are in parent process
close(fds[0]); // file descriptor unused in parent
const char *words[] = {"pear", "peach", "apple"};
// write input to the writable file descriptor so it can be read in from child:
size_t numwords = sizeof(words)/sizeof(words[0]);
for (size_t i = 0; i < numwords; i++) {
dprintf(fds[1], "%s\n", words[i]);
}
// send EOF so child can continue (child blocks until all input has been processed):
close(fds[1]);
int status;
pid_t wpid = waitpid(pid, &status, 0); // wait for child to finish before exiting
return wpid == pid && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
For "sort" command, the output is:
$ ./example
apple
peach
pear
For "test1" , the output is:
$ ./example
hello!
test1
If it is working for "test1", the output should be:
$ ./test1 pear peach apple
hello!
./test1
pear
peach
apple
test1.c
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char** argv){
printf("hello!\n");
for(int i = 0; i < argc; i++){
printf("%s\n", argv[i]);
}
return 0;
}
What am I doing wrong?

test1 doesn't read any input, so passing it input doesn't work.
To get your sample output have test1 execl cat.

Related

Father-child process use pipe to talk, hangs after "execlp", why?

I've got a simple text file called "tmp" under current directory, I wish to "cat" this file and then "sort" it, I want to use a c program to act like pipe "|" so I tried to use a father/child talk to do this.
Unexpectedly, the program hangs after "cat", like below:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd=pipefd[0];
int& writefd=pipefd[1];
pid_t pid=fork();
if(pid==0){//child
dup2(STDIN_FILENO,writefd);
close(readfd);
execlp("cat","cat","tmp",NULL);
printf("child cat ends\n");
exit(0);
}else{//father
dup2(STDOUT_FILENO,readfd);
close(writefd);
execlp("sort","sort",NULL);
printf("father sort ends\n");
}
int status;
wait(&status);
printf("father exists\n");
return 0;
}
g++ to compile and run this file, after "cat" tihis file, I don't even see "child cat ends", it just hangs.
Where's the problem, how to fix it?
Thanks
1) The order of arguments in dup2 is incorrect. Look at dup2
2) parameters (stdin/stdout) to dup2 are incorrect.
3) The exec() family of functions replace the process image with a new one. So the code after that call does not get to run (unless the exec() fails), so I removed those.
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd = pipefd[0];
int& writefd = pipefd[1];
pid_t pid = fork();
if(pid == 0){ //child
dup2(writefd, 1); // 1 is STDOUT_FILENO -- cat already has input -- needs output
close(readfd);
execlp("cat","cat","tmp.txt", NULL);
perror("execlp() failed in child");
}else{ //father
dup2(readfd, 0); // 0 is STDIN_FILENO -- because sort needs input!
close(writefd);
execlp("sort","sort", NULL);
perror("execlp() failed in parent");
}
return 0;
}

Can't write to pseudo terminal master

I'm able to open a new pseudo terminal, and start a shell on the slave, but writing to the master doesn't seem to do anything, and trying to read after the shell has started ends in failure (-1). What am i doing wrong:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ioctl.h>
int posix_openpt(int flags);
int grantpt(int fd);
int unlockpt(int fd);
char *ptsname(int fd);
static void execsh(void);
int main(int argc, char *argv[]) {
printf("Hiya\n");
// Open the Master Clone Device /dev/ptmx, return the fd
int master_fd = posix_openpt(O_RDWR);
printf("PTMaster = %d\n", master_fd);
// Change the permissions and ownership of the slave device
int grant_success = grantpt(master_fd);
printf("Grant success = %d\n", grant_success);
// Unlock the slave pseudoterminal device corresponding to master_fd
int unlock_success = unlockpt(master_fd);
printf("Unlock success = %d\n", unlock_success);
// Grab the name of the slave device
char *slave_name = ptsname(master_fd);
printf("Slave name = %s\n", slave_name);
// Open the slave pseudoterminal device
int slave_fd = open(slave_name, O_WRONLY);
printf("Slave fd = %d\n", slave_fd);
// Exec shell
pid_t pid;
switch (pid = fork()) {
case -1:
printf("Failed to fork\n");
break;
case 0:
// Child
setsid(); /* create a new process group */
dup2(slave_fd, STDIN_FILENO);
dup2(slave_fd, STDOUT_FILENO);
dup2(slave_fd, STDERR_FILENO);
ioctl(slave_fd, TIOCSCTTY, NULL); /* make this the controlling terminal for this process */
close(slave_fd);
close(master_fd);
// Start Shell
execsh();
break;
default:
// Parent
close(slave_fd);
}
// Read from master
sleep(1);
char buffer[200];
ssize_t read_bytes = read(master_fd, buffer, 200);
printf("read %ld from master\n", read_bytes);
printf("buffer = %s\n", buffer);
// ls
ssize_t written = write(master_fd, "ls\n", 3);
printf("wrote %ld to master\n", written);
// Read from master
read_bytes = read(master_fd, buffer, 200);
printf("read %ld from master\n", read_bytes);
printf("buffer = %s\n", buffer);
close(master_fd);
kill(pid, SIGKILL); // Kill the child, biblical
return 0;
}
void
execsh(void) {
char **args;
char *envshell = getenv("SHELL");
unsetenv("COLUMNS");
unsetenv("LINES");
unsetenv("TERMCAP");
signal(SIGCHLD, SIG_DFL);
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGALRM, SIG_DFL);
args = (char *[]){envshell, "-i", NULL};
printf("\nforked child starting terminal\n");
execvp(args[0], args);
printf("\nExited the shell\n");
exit(EXIT_FAILURE);
}
output looks like this:
Hiya
PTMaster = 3
Grant success = 0
Unlock success = 0
Slave name = /dev/pts/19
Slave fd = 4
read 130 from master
buffer =
forked child starting terminal
eric#vbox:~/Desktop/terminal$ exit
wrote 3 to master
read -1 from master
buffer =
forked child starting terminal
eric#vbox:~/Desktop/terminal$ exit
I'm not sure why it has the word exit there either. Thanks in advance for any pointers you might have!
ninjalj was right. I had the slave opened for writing only.
Thank you very much!

Does the CHILD_SUBREAPER bit persist across fork()?

When a process sets the child subreaper bit with prctl(PR_SET_CHILD_SUBREAPER, 1) (documented here), does it need to use prctl(PR_SET_CHILD_SUBREAPER, 0) to clear it after a fork?
No, the child subreaper bit does not persist across forks.
The relevant Linux kernel code is in copy_signal() in kernel/fork.c: the signal struct is initialized to all zeros, and the is_child_subreaper bit is never set.
However, has_child_subreaper is set:
sig->has_child_subreaper = current->signal->has_child_subreaper ||
current->signal->is_child_subreaper;
This test program demonstrates the behavior:
#include <stdio.h>
#include <stdlib.h>
#include <sys/prctl.h>
int main(int argc, char** argv) {
int pid;
int i;
prctl(PR_SET_CHILD_SUBREAPER, 1);
prctl(PR_GET_CHILD_SUBREAPER, &i);
printf("Before fork: %d\n", i);
pid = fork();
if (pid < 0) {
return 1;
} else if (pid == 0) {
prctl(PR_GET_CHILD_SUBREAPER, &i);
printf("In child: %d\n", i);
return 0;
}
return 0;
}
Outputs:
Before fork: 1
In child: 0

IPC - How to redirect a command output to a shared memory segment in child

I tried to redirect (write) a Unix command output to a shared memory segment in the child,
and then have the parent read the output back out from the same shared memory segment in the parent process. I don't have a lot of success after few futile attempts. Can anyone show me a way?
thanks in advance.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
key_t key; int shmid; char* data;
pid_t cpid=fork();
if (cpid<0)
{
fprintf(stderr,"Fork error!\n");
exit (-1);
}
else if (cpid==0) // child process
{
if ((key = ftok("mysh.c", 'R')) == -1)
{
perror("ftok");
exit(1);
}
// Connect to shared memory
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1)
{
perror("shmget");
exit(1);
}
// Attach to the segment
data = shmat(shmid, (void *) 0, 0);
if (data == (char *) (-1))
{
perror("shmat");
exit(1);
}
system("ls -l");
// Stuck: How to redirect the output of "ls -l"
// to a shared memmory segment "data", so that parent process
// can retrieve it later?? Tried to
// do pipe and dup2 but none worked.
// Attempt via read?, but only garbage
read(STDIN_FILENO, data, SHM_SIZE);
}
else
{ // parent process
int st;
wait(&st);
printf("Output read from the child:\n");
if ((write(STDOUT_FILENO, data, SHM_SIZE)) < 0 )
{
perror("write 2");
exit(1);
}
}
}
======================
system("ls -l");
// Stuck: How to redirect the output of "ls -l"
// to a shared memmory segment "data", so that parent process
// can retrieve it later?? Tried to
// do pipe and dup2 but none worked.
For test purpose, I suggest you read from stdin, then write them to data.
Here is an example using POSIX shared memory (POSIX IPC API is better than SYSV IPC API), which child read from stdin to a shared memory region, and parent write the content of this shared memory region to stdout:
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
const char *shm_name = "/dummy_cat_shm";
int shm_fd;
off_t shm_length;
const char *read_sem_name = "/dummy_cat_read";
const char *write_sem_name = "/dummy_cat_write";
sem_t *read_sem, *write_sem;
pid_t pid;
int buf_length;
char *write_ptr, *read_ptr;
buf_length = 1024;
shm_length = sizeof(buf_length) + buf_length;
/* Create semaphore */
read_sem = sem_open(read_sem_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR, 0);
if (read_sem == SEM_FAILED) {
perror("sem_open");
goto clean_up3;
}
write_sem = sem_open(write_sem_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR, 1);
if (write_sem == SEM_FAILED) {
perror("sem_open");
goto clean_up2;
}
/* Create shared memory segment */
shm_fd = shm_open(shm_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (shm_fd < 0) {
perror("shm_open");
goto clean_up1;
}
if (ftruncate(shm_fd, shm_length) < 0) {
perror("ftruncate");
goto clean_up0;
}
if ((pid = fork()) < 0) {
perror("fork");
goto clean_up0;
}
else if (pid == 0) {
write_ptr = mmap(NULL, shm_length, PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (write_ptr == MAP_FAILED) {
perror("mmap");
goto clean_up0;
}
char *buf = write_ptr+sizeof(buf_length);
while (sem_wait(write_sem) == 0) {
if (fgets(buf, buf_length, stdin) != NULL) {
*(int *)write_ptr = 1;
sem_post(read_sem);
}
else {
*(int *)write_ptr = 0;
sem_post(read_sem);
break;
}
}
munmap(write_ptr, shm_length);
}
else {
read_ptr = mmap(NULL, shm_length, PROT_READ, MAP_SHARED, shm_fd, 0);
if (read_ptr == MAP_FAILED) {
perror("mmap");
goto clean_up0;
}
char *buf = read_ptr + sizeof(buf_length);
while (sem_wait(read_sem) == 0) {
if (*(int *)read_ptr > 0) {
printf("%s", buf);
sem_post(write_sem);
}
else {
break;
}
}
munmap(read_ptr, shm_length);
}
clean_up0:
shm_unlink(shm_name);
clean_up1:
sem_unlink(write_sem_name);
clean_up2:
sem_unlink(read_sem_name);
clean_up3:
exit(EXIT_FAILURE);
}
Note: these two mmap() could be put before fork() in this case.
Compiling:
gcc shm_exp.c -pthread -lrt
Running:
$ ls / | ./a.out
bin/ home/ lib32/ mnt/ run/ sys/ vmlinuz#
boot/ initrd.img# lib64/ opt/ sbin/ tmp/ vmlinuz.old#
dev/ initrd.img.old# lost+found/ proc/ selinux/ usr#
etc/ lib/ media/ root/ srv/ var/
How to redirect stdout of the ls -l
We must shed more light on the processes (parent and children) involved into this code.
How many processes your program creates during its run?
The correct answer is - three.
Two processes are the parent and the explicitly forked child.
The third one is created by the system("ls -l") call.
This function implicitly forks another process that executes (by calling an exec family function) the "ls -l" sell command. What you need to redirect is the output of the child process created by the system() function. It is sad, but the system() does not establish IPC between the participators. If you need to manipulate with the output, do not use system().
I agree with #leeduhem, popen() could be the best approach.
It works exactly as the system(), i.e. forks a new process and executes "ls -l".
In addition, it also establishes a pipe IPC between the participators, so it is easy to catch the child output and to do with it whatever you want:
char buff[1024];
FILE *fd;
// instead of system("ls -l")
fd = popen("ls -l", "r");
// check for errors
while(fgets(buff, sizeof(buff), fd) != NULL)
{
// write to the shared memory
}
pclose(fd);
If you do not want to use the popen() function, you may write a similar one.
The general approach is
open a pipe()
fork() a new process
redirect stdout using dup2
call a suitable exec() function (probably execl()) executing "ls -l"
read from the descriptor you are duplicating by dup2.

Print fifo content and exit

I need to print the content of a fifo (named pipe) to standard output.
I could use the command:
cat fifo
The problem is that cat doesn't return. It stays running, waiting for more content coming from the fifo. But I know there wont be any more content coming for a while so I just want to print what's available.
Is there a command that just print the available content and exit??
EDIT:
In one end of the fifo there is a process writing every now and then the output of different commands. That process is permanently running so there wont be an EOF.
When you can't send an EOF, you could use a 'non-blocking cat'. I've included a (tested) C version i found here (credit goes to the original author over there of course). The magic is in fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK).
The first argument to this non-blocking cat is the number of seconds you want to wait before exiting again.
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
void read_loop(int fFile, double wWait)
{
if (fFile < 0) return;
double max_time = wWait, total_time = 0;
struct timespec cycle_time = { 0, 50 * 1000 * 1000 };
double add_time = (double) cycle_time.tv_sec + (double) cycle_time.tv_nsec / 1000000000.;
char next_line[1024];
FILE *input_file = fdopen(fFile, "r");
while (total_time < max_time)
{
while (fgets(next_line, 1024, input_file))
{
write(STDOUT_FILENO, next_line, strlen(next_line));
total_time = 0;
}
nanosleep(&cycle_time, NULL);
total_time += add_time;
}
fclose(input_file);
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "%s [max time] (files...)\n", argv[0]);
return 1;
}
int max_wait = strtoul(argv[1],0, 10);
if (argc == 2)
{
fprintf(stderr, "%s: using standard input\n", argv[0]);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
read_loop(STDIN_FILENO, max_wait);
return 0;
}
int current = 2;
while (current < argc)
{
fprintf(stderr, "%s: switch to file '%s'\n", argv[0], argv[current]);
int next_file = open(argv[current++], O_RDONLY | O_NONBLOCK);
read_loop(next_file, max_wait);
close(next_file);
}
return 0;
}
You should close the other end of the FIFO. That should send an EOF to the cat process.

Resources