Linux Pipes and Redirecting output - linux

I'm trying to write a linux program using pipes, but so far I've encountered a major problem.
When I try to run this, it seems it either duplicates the answers, or doesnt give me an answer at all.
So far I'm trying to use a pipe, the parent gets a string from the keyboard, and compares it to see if matches any other commands, momentarily its only the "login" command.
But it doesnt work as it doesnt show me a fail or success message. I've been fiddeling with the code, but sometimes it's repeating the answer several time, like it's executing the child several times. Can someone explain me why its happening?
Thx
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int fd[2], nbytes;
pid_t childpid;
char input[12];
char readbuffer[80];
int log_variable;
int pid;
int compare(char str1[], char str2[]){
if(strlen(str1) == strlen(str2))
{int i;
for( i=0; i<strlen(str1); i++){
if(str1[i] != str2[i])
return 0;
return 1;
}
}
}
int test(char argument[]){//test function
pipe(fd);
switch(childpid=fork()){
case -1:
perror("fork -1\n");
exit(1);
case 0://child
close (fd[1]);
int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
if(compare(readbuffer, "login") == 1){
return 1;
}
else if(compare(readbuffer, "login") == 0){
return 0;
}
exit(1);
default:
//parent
close(fd[0]);
write(fd[1], argument, sizeof(argument));
while(wait(NULL)!=-1);
}
}
main(){
while(1){
printf("Insert command: \n");
scanf("%s", input);
logs=(test(input));
if(logs == 1) {printf("success\n"); break;}
else if(logs == 0) {printf("fail\n"); continue;}
}
return 0;
}

a couple of problems for your code with a quick look:
compare function doesn't return value if length not equal.
test() function may get called twice in one process, which means fork more times.
the test() internally for the child will return to the main, also parent will return to main ... get things more complicated here (the child may fork a third time ...)
Use "strace -F" can give you a much better view what things happened behind.

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;
}

What's the intention of waitpid

The sample code below is from linux man page waitpid function. Can the last else if be replaced with else? When I write code, I would write like:if, else if, and end with else. So I think it is strange in the sample code.
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Code executed by child */
printf("Child PID is %ld\n", (long) getpid());
if (argc == 1)
pause(); /* Wait for signals */
_exit(atoi(argv[1]));
} else { /* Code executed by parent */
do {
w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
if (w == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) { /* can this be
*replaced with else ???
*/
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
}
Here's the question I think you are asking:
Is it possible for waitpid to return a status such that none of
WIFEXITED(status), WIFSIGNALED(status), WIFSTOPPED(status), or
WIFCONTINUED(status) returns nonzero?
The answer is almost certainly "no", and the Linux man page implies as much without (unfortunately) explicitly saying it.
The UNIX standard says more here, and specifically does guarantee that one of those macros will return nonzero in certain cases. But Linux is not (necessarily) compliant to this standard.
But I think the best solution in code would be to have an else clause after those four options, and (depending on your application) take this to mean that the status is unknown. This could happen even if it's not the case now - maybe in some future version of Linux there is another kind of exit condition not covered here, and you don't want your code to crash in such a case.
The standard does seem to have evolved over time. For example, earlier versions didn't have the WIFCONTINUED case, and I also found some references online to a WIFCORED in some other systems. So it would be good to make your code flexible if you're concerned about it.

Why the program didn't execute some sentences in this C programming or unix programming(execvp() System calls)?

I have the following program, when I run the program, I feel really confused that why my program didn't excute
int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");
My program basically create 6 child processes to excute executionbode() function, and then use execvp to overload original program. However, everytime when I run the program, the string "hello, I will execute execvp" never shows up! Also I think those three sentences above also didn't execute in the running program? can someone tell me why? Here is my program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include "makeargv.h"
#include "redirection.h"
#include <sys/wait.h>
int executionnode(int i);
int main(){
pid_t childpid;
int i;
int row=6;
for(i=0;i<row;i++)
{ childpid=fork();
if(childpid==0)
continue;
else if (childpid>0)
executionnode(i);
else {
perror("something wrong");
exit(1);
}
}
}
int executionnode(int i){
sleep(i);
printf("hello, I am process:%ld\n",(long)getpid());
wait(NULL);
char *execArgs[] = { "echo", "Hello, World!", NULL };
int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");
execvp("echo", execArgs);
}
Can someone tell me why? and how to fix it? I feel it is really strange? Is it because of execvp() functions? I just began to learn operating system,so I am really confused about it! Thank you for helping me!
As user3629249 said you have some confusion. You'll get many children of children of children... and that wait(NULL) is useless :).
I used this structure to got your goal in my OS subject excercises.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#define N 5
int main(int argc, char const *argv[])
{
pid_t pid,pids[N];
int i, num_pids = 0;
int state = 0;
int prior[]={1,3,5,2,4};
pid_t parent_pid = getpid();
printf("Parent pid is %i\n",father_pid);
// This for loop is the key
for (i = 0; i < N && getppid() != parent_pid; i++)
{
if ((pid = fork()) < 0)
{
printf ("fork error\n");
exit(-1);
}
pids[num_pids++] = pid;
}
if (pid == 0) // Child processes
{
printf("I am the child %i\n",getpid());
}
else // Parent process
{
for (i = 0; i < N; i++)
{
int pid_index = prior[i]-1; // Array starts with 0
pid = waitpid(pids[pid_index]);
printf("Children %i ended\n",pids[indice_pid]);
printf("%i alive children\n",N-1-i);
}
}
return 0;
}
This structure works because you save the parent's pid in parent_pid variable and compare the parent of each process pid with getppid(). If this pid is different that parent_pid, this proccess is the parent. In another case the process is a child so it has to stop (these processes don't have to fork). With this way you can get only the forks you need.
The rest of the code is the same: Pid==0 is child process and any other is the parent. You can call executionnode(int i) in child processes block (remember, pid==0 !!! you have a mistake). i variable should have the right value in each call I think.
Good luck!

how do i check if execv function faild or succeeded?

i got an assignment to write a simple linux shell ,
this is the code so far :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc,char argv[])
{
char *token;
char command[50];
char tmp[256];
char *arg_command[]={"",0};
int pid,status,flag=0;
char *path = (char*)getenv("PATH");
while(1) // run always
{
printf("\n");
printf(getenv("PWD")); //print current dir
printf(": ");
gets(command);
if (strcmp(command,"exit")==0) //check for exit command
{
printf("bye\n");
break;
}
strcpy(tmp,path);
token = strtok(path,":");
while(token!=NULL)
{
arg_command[0] = command;
pid = fork();
if(pid>=0)
{
printf("\npid is:%d\n",pid);
if (pid==0) // child process is invoked
{
strcat(token,"/");
execv(strcat(token,command),arg_command);
exit(0);
}
else //parent process
{
wait(&status);
if(status==0)
}
}
else
{
printf("fork faild");
}
token = strtok(NULL,":");
}
if (flag == 1)
{
printf("no files or folders match this command\n");
}
strcpy(path,tmp);
}
return 0;
}
my question is how do i know whether execv was able to execute the command or not
because i want to output an error when ever the user entered a wrong command.
i also have a flag but because i cant check execv i cant use it .
Like most Unix/POSIX functions, exec* return an error code (-1) if they fail. errno will then tell you why it failed.
In fact, if they ever return, then something went wrong. Otherwise, the current process is replaced which means no code after is ever execute (exit(0) in your case).

Multithreading Semaphore

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
void *thread_function(void *arg);
sem_t bin_sem;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = sem_init(&bin_sem, 0, 0);
if (res != 0) {
perror(“Semaphore initialization failed”);
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0) {
perror(“Thread creation failed”);
exit(EXIT_FAILURE);
}
printf(“Input some text. Enter ‘end’ to finish\n”);
while(strncmp(“end”, work_area, 3) != 0) {
fgets(work_area, WORK_SIZE, stdin);
sem_post(&bin_sem);
}
printf(“\nWaiting for thread to finish...\n”);
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror(“Thread join failed”);
exit(EXIT_FAILURE);
}
printf(“Thread joined\n”);
sem_destroy(&bin_sem);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg) {
sem_wait(&bin_sem);
while(strncmp(“end”, work_area, 3) != 0) {
printf(“You input %d characters\n”, strlen(work_area) -1);
sem_wait(&bin_sem);}
pthread_exit(NULL);
}
In the program above, when the semaphore is released using sem_post(), is it
possible that the fgets and the counting function in thread_function execute
simultaneously .And I think this program fails in allowing the second thread
to count the characters before the main thread reads the keyboard again.
Is that right?
The second thread will only read characters after sem_wait has returned, signaling that a sem_post has been called somewhere, so I think that is fine.
As for fgets and the counting function, those two could be running simultaneously.
I would recommend a mutex lock on the work_area variable in this case, because if the user is editing the variable in one thread while it is being read in another thread, problems will occur.
You can either use a mutex or you can use a semaphore and set the initial count on it to 1.
If you implement a mutex or use a semaphore like that though, make sure to put the mutex_lock after sema_wait, or else a deadlock may occur.
In this example you want to have a mutex around the read & writes of the shared memory.
I know this is an example, but the following code:
fgets(work_area, WORK_SIZE, stdin);
Should really be:
fgets(work_area, sizeof(work_area), stdin);
If you change the size of work_area in the future (to some other constant, etc), it's quite likely that changing this second WORK_SIZE could be missed.

Resources