Loop fails to continue looping - c

I was working on some code to create a new folder everytime a specific FIFO is written to:
int main (int argc, char* argv[]) {
if (argc != 2) {
printf("Usage: %s <directory>\n",argv[0]);
exit(0);
}
int ret = chdir(argv[1]);
if (ret < 0) {
printf("Could not chdir to %s\n",argv[1]);
perror("");
exit(0);
}
ret = mkfifo("create",0666);
if (ret < 0) {
perror("Could not make create fifo");
return 0;
}
int ctfd = open("create",O_RDWR);
if (ctfd < 0) {
perror("Could not open create");
return 0;
}
char create[1];
//socket counter
int count = 0;
char crdir[15];
for(;;ret = read(ctfd,create,1)) {
//printf("%s %d\n",create,count);
if (ret < 0) {
perror("Failed to read from create");
continue;
}
else if (ret < 1 || create[0] == '\n') {
continue;
}
sprintf(crdir,"%d",count);
ret = mkdir(crdir,0777);
if (ret < 0) {
printf("Failed to create dir");
perror("");
continue;
}
count++;
switch(fork()) {
case -1:
perror("Failed to fork");
break;
case 0:
printf("%d\n",count);
break;
default:
//char* argv[ ] = {"netclient",cte};
exit(0);
}
printf("test");
}
//execvp()
return 0;
}
However when run this happens:
arthur#dent:~/coding/netdir$ mkdir test
arthur#dent:~/coding/netdir$ ./netserver test &
[1] 2122
arthur#dent:~/coding/netdir$ echo 1 > test/create
[1]+ Done ./netserver test
1
What did I do wrong? Why does it not continue looping and wait for more input?
The FIFO is opened for reading and writing so that it would not be closed when the writing stopped, did that not work properly?

Taking a second look, I would say your problem is in switch( fork() ).
fork() returns 0 for the child process and the child's PID for the parent but you have exit(0); in default: so you exit the parent.
Another problem (seen first):
Your loop is:
for(;;ret = read(ctfd,create,1)) {
do_something;
}
which is equal to:
while( 1 ) {
do_something;
ret = read(ctfd,create,1);
}
do you 'do something' before reading. That leads to Undefined Beahaviour, e.g. becaus the contents of create isn't defined.

Related

Creating Shell in C - Piping and External Commands

I am trying to create a small shell using C. At the moment I am trying to figure out piping and external commands. I got stuck in them both even after looking at various youtube videos.
I referred to MAN and even Advanced Linux Programming
What can I change to improve and make the implementation work?
This a part of the checking of commands, args := tokenisation by whitespace, commLHS := will be used to store args before | and commRHS will be used to store args after | and indexT refers to the number of arguments inputted
else if((check4pipe(args, commLHS, commRHS, indexT) != 0))
{
return runPipeComm(commLHS, commRHS);
//fprintf(stderr, "%s: command not found\n", args[0]);
}
This will execute External Commands
void externalCommands(char **args)
{
// fork-plus-exec pattern
// https://www.percona.com/community-blog/2021/01/04/fork-exec-wait-and-exit/
/*
First we Fork
Then we Exec
Then we Wait
Then we Exit
*/
int status;
pid_t pip = fork();
if (pip == -1)
{
perror("Error - fork()");
}
else if (pip == 0)
{
//If PID is the child process
//Launches the process.
if (execvp(args[0], args) < 0)
{
perror("Error - execvp()");
}
}
else
{ //If PID is the parent process.
//Waits for the child process and returns exit code if waitpid() is successful.
if(waitpid(pip, &status, WUNTRACED) == -1)
{
perror("Error occured during waitpi");
}
else
{
//set_exitcode(status); //Sets the exitcode environment variable.
}
}
}
This is to check for | in args inputted by user after tokenisation.
int check4pipe(char **args, char **pipeLHS, char **pipeRHS, int indexT)
{
bool foundPipe = false;
for(int i = 0; i < indexT; i++)
{
if(strcmp(args[i], "|") == 0)
{
foundPipe = true;
memcpy(pipeLHS, args, (i+1) * sizeof(char*));
pipeLHS[i] = NULL;
memcpy(pipeLHS, args+(i+1), ((indexT-i)+1) * sizeof(char*));
pipeRHS[i]= NULL;
}
else
{
continue;
}
}
if(foundPipe == true)
{
return 1;
}
else
{
return 0;
}
}
This will run the pipe commands
int runPipeComm(char **commLHS, char **commRHS)
{
int userPipe[2];
pid_t pip1; // Pipe ID 1
pid_t pip2; // Pipe ID 2
if(pipe(userPipe) < 0)
{
perror("Error Occurred while piping: ");
}
// Start Process
pip1 = fork();
if(pip1 == -1)
{
perror("Error Occurred while forking: ");
}
else if(pip1 == 0)
{
dup2(userPipe[1], STDOUT_FILENO);
close(userPipe[1]);
//run
exit(0);
}
else
{
pip2 = fork();
if(pip2 == -1)
{
perror("Error Occurred while forking: ");
}
else if(pip2 == 0)
{
dup2(userPipe[0], STDOUT_FILENO);
close(userPipe[1]);
//run
exit(0);
}
else
{
close(userPipe[0]);
close(userPipe[1]);
wait(NULL);
wait(NULL);
}
}
return 1;
}
You forgot to change some things when copying snippets within your program.
wrong:
memcpy(pipeLHS, args+(i+1), ((indexT-i)+1) * sizeof(char*));
pipeRHS[i]= NULL;
right:
memcpy(pipeRHS, args+(i+1), (indexT-(i+1)) * sizeof (char*));
pipeRHS[indexT-(i+1)] = NULL;
wrong:
dup2(userPipe[0], STDOUT_FILENO);
close(userPipe[1]);
right:
dup2(userPipe[0], STDIN_FILENO);
close(userPipe[0]);
After the first //run line, add the missing
execvp(*commLHS, commLHS);
perror("Error - execvp()");
After the second //run line, add the missing
execvp(*commRHS, commRHS);
perror("Error - execvp()");
Finally, the write end of the pipe must be closed in the parent process, so move the close() there:
close(userPipe[1]);
pip2 = fork();

Trying to append to existing file in c in my own Unix Shell using >> not working

I'm trying to create my own unix shell and I've hit a wall while trying to append a command such as ls to an existing file, for example.
ls >> myOutput
I was able to do a basic redirection using > to print to an output file and figured doing >> would be quite similar, but I guess I'm wrong.
This is my code:
int pid;
int in = 0, out = 0, append = 0, j;
int fd0, fd1, fda;
char* args[MAX_ARGS];
char inFileName[64], outFileName[64];
//used to get arguments for desired command
//i.e. ls -a -l -t
get_args(cmdline, args);
//Commands used to exit the shell.
if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit"))
{
exit(0);
}
pid = fork();
if(pid == 0)
{ /* child process */
for(j = 0; args[j] != '\0'; ++j)
{
if(strcmp(args[j], ">>") == 0)
{
args[j] = NULL;
strcpy(outFileName, args[j + 1]);
printf("You want to append data to existing file\n");
append = 2;
}
if(strcmp(args[j], "<") == 0)
{
args[j] = NULL;
strcpy(inFileName, args[j + 1]);
printf("input file name is %s\n", inFileName);
in = 2;
}
if(strcmp(args[j], ">") == 0)
{
args[j] = NULL;
strcpy(outFileName, args[j + 1]);
printf("output file name is %s\n", outFileName);
out = 2;
}
}
//printf("in is %d and out is %d\n", in, out);
if(!strcmp(args[0], "|"))
{
printf("You want to pipe info\n");
}
if(append)
{
**//here is where my issue occurs**
if((fda = open(outFileName, O_RDWR|O_APPEND)) < 0)
{
perror("Error appending data\n");
exit(0);
}
dup2(fda, STDOUT_FILENO);//1
close(fda);
}
if(in)
{
if((fd0 = open(inFileName, O_RDONLY, 0)) < 0)
{
perror("Couldn't read from input file\n");
exit(0);
}
//Changes where the command will read from STDIN to a input file.
dup2(fd0, 0);
close(fd0);
}
if(out)
{
if((fd1 = creat(outFileName , 0644)) < 0)
{
perror("Coudln't create output file\n");
exit(0);
}
dup2(fd1, STDOUT_FILENO);//1
close(fd1);
}
execvp(*args, args);
perror("exec failed");
exit(-1);
}
else if(pid > 0)
{ /* parent process */
waitpid(pid, NULL, 0);
}
else
{ /* error occurred */
perror("fork failed");
exit(1);
}
Please let me know if you would like further details. Any help would truly be appreciated.

C pipe: Bad file descriptor

I have the simple producer consumer program in C try to solve it with fork
I get error exactly when producer tries to write on pipe:
I have wrote another program with the same logic but this one does not give me any clue to know why?
Producer failed to write item on pipe: Bad file descriptor
Anyone have idea why I get this error?
Thanks
#define READ 0
#define WRITE 1
int mutex = 1, full = 0, empty = BUFFER_SIZE, x = 0;
void consumer();
void producer();
int wait_(int);
int signal_(int);
int pipefd[2];
int main() {
printf("Starting producer-consumer problem!\n");
//We intend to run the producer in parent process and the consumer in the child process
if (pipe(pipefd) == -1) { /* An error has occurred. */
fprintf(stderr, "%s", "The call to pipe() has failed.\n");
exit(EXIT_FAILURE);
}
for (int j = 0; j < sizeof(pipefd); j++) {
if (pipe(&pipefd[j]) < 0) { //Initialize each pipe appropriately
perror("Error in making pipe...");
}
}
pid_t pid = fork();
if (pid < 0) {
perror("**********Error in creating fork()!**************\n");
exit(STDERR_FILENO);
} else if (pid == 0) {
consumer();//We intend to run the consumer in child
} else {
producer();//We intend to run the producer in parent
}
return 0;
}
int wait_(int s) {
return (--s);
}
int signal_(int s) {
return (++s);
}
void producer() {
printf("Starting Producer\n");
//while (1) {
//sleep(1);
if (close(pipefd[READ]) != 0) {
perror("Error in closing reading pipe");
}
if (write(pipefd[WRITE], &full, 1) < 0) {
perror("Producer failed to write item on pipe");
}
if ((mutex == 1) && (empty != 0)) {
mutex = wait_(mutex);
full = signal_(full);
empty = wait_(empty);
x++;
printf("Producer produces the item %d\n", x);
mutex = signal_(mutex);
}
if (close(pipefd[WRITE]) != 0) {
perror("Error in closing writing pipe");
}
//}
}
void consumer() {
printf("Starting Consumer\n");
//while (1) {
//sleep(1);
int status = 0;
wait(&status); /* wait for all children to return back the result */
if (close(pipefd[WRITE]) != 0) {
perror("Error in closing reading pipe");
}
if (read(pipefd[READ], &full, 1) > 0) {
printf("Consumer\t%d\n", full);
}
if ((mutex == 1) && (full != 0)) {
mutex = wait_(mutex);
full = wait_(full);
empty = signal_(empty);
printf("Consumer consumes item %d\n", x);
x--;
mutex = signal_(mutex);
}
if (close(pipefd[READ]) != 0) {
perror("Error in closing reading pipe");
}
//}
}
The sizeof operator returns the size in bytes. So on a typical system where an int is four bytes, sizeof(pipefd) would result in the value 8. Which is not the correct number of elements for your loop.
Also, pipe(&pipefd[j]) is not correct either. The two pipes in pipefd are already initialized "appropriately". There's no need for any more initialization. Especially since in both this and the previous case you will have undefined behavior.

Pass parameter to another function using C

int main(void){
int n, user_length;
char userid[30];
char password[11];
if ((n = read(STDIN_FILENO, userid, 10)) == -1) {
perror("read");
exit(1);
} else if(n == 0) {
fprintf(stderr, "Error: could not read from stdin");
exit(1);
}
if (userid[n-1] == '\n')
userid[n-1] = '\0';
else
userid[n] = '\0';
if ((n = read(STDIN_FILENO, password, 10)) == -1) {
perror("read");
exit(1);
} else if (n == 0) {
fprintf(stderr, "Error: could not read from stdin");
exit(1);
}
if (password[n-1] == '\n')
password[n-1] = '\0';
else
password[n] = '\0';
strcat(userid, ":");
user_length = strlen(userid);
strcat(userid, password);
FILE *fp = fopen(PASSWORD_FILE, "r");
if (!fp) {
perror("fopen");
exit(1);
}
char line[MAXLINE];
while(fgets(line, sizeof(line) - 1, fp)) {
line[strlen(line) - 1] = '\0';
if (strcmp(userid, line) == 0)
exit(0); // found match
else if(strncmp(userid, line, user_length) == 0)
exit (2); // invalid password
}
exit(3); // no such user
}
Above is the implementation of validate.c, but how do I pass value such as userid and password to the function by using pipe(),dup2 or execl()
I used the following`
int main(void) {
char userid[10];
char password[10];
int pid;
int p[2][4];
char other[MAXSIZE];
/* Read a user id and password from stdin */
printf("User id:\n");
scanf("%s", userid);
printf("Password:\n");
scanf("%s", password);
/*Your code here*/
if (pipe(p[1]) == -1) {
perror("pipe");
}
if (pipe(p[0]) == -1) {
perror("pipe");
}
pid = fork();
if (pid != 0) {
close(p[1][0]);
close(p[0][0]);
dup2(p[1][1],STDIN_FILENO);
dup2(p[0][1],STDIN_FILENO);
close(p[1][1]);
close(p[0][1]);
int status;
if (wait(&status)!= -1) {
if (WIFEXITED(status)) {
printf("[%d] Child exited with %d\n", getpid(), WEXITSTATUS(status));
switch(WEXITSTATUS(status)){
case 0:
printf("found match\n");
break;
case 2:
printf("invalid password\n");
break;
case 3:
printf("No such user\n");
break;
default:
printf("error has occur\n");
break;
};
} else {
printf("[%d] Child exited abnormally\n", getpid());
}
}
} else if (pid == 0) {
close(p[1][1]);
close(p[0][1]);
dup2(p[1][0], fileno(stdout));
dup2(p[1][0], fileno(stdout));
execl("validate",other);
printf("what\n");
close(p[1][0]);
close(p[0][0]);
} else {
perror("fork");
exit(1);
}
return 0;
}
But the prompt always asks me for re-entering the input. What is wrong with this approach?( Note: I "execl" "validate" because it is an executable file that has been already created. The execl() I wrote simply calls the validate.c function )
As I said in the comments you probably do not need to spawn another process for this but You have an error in the way you call execl.
This:
execl("validate",other);
Should be:
execl(filename,list of arguments, NULL);
This is the documentation page. They use (char *) 0 which is the same as using NULL.

I am having trouble redirecting my output back from file to standard out C

I have looked all over the internet and die.net and can't see to make my code work. My problem is that I am able to redirect the output to a file, but have trouble bringing it back to standard out, I have tried using dup, dup2 and close, but maybe I am using them wrong. Any help would be appreciated, thank you
. My problem begins at the if(myargc >= 3) block when I am trying to redirect the output.
main()
{
int i, myargc =0, background, newfile, file, stdout2, read = 0, write = 0;
pid_t pid;
char input[512], *myargv[60];
while(1)
{
background = 1;
printf("Myshell>");
gets(input);
//scanf("%s", input);
myargc = parser(input, myargv);
if(strcmp(*myargv, "exit") == 0)
{
exit(0);
}
if(strcmp(myargv[myargc-1], "&") == 0)
{
background = 0;
myargv[myargc-1] = '\0';
myargc--;
}
if(myargc >= 3)
{
if(strcmp(myargv[myargc-2], ">") == 0)
{
write = 1;
file = creat(myargv[myargc-1], S_IWUSR);
myargv[myargc-2] = '\0';
if(file < 0)
{
printf("File could not be created.\n");
}
printf("Redirecting output to file %s.\n", myargv[myargc-1]);
fflush(stdout);
stdout2 = dup(STDOUT_FILENO);
//fclose(stdout); // fclose() for type FILE*
newfile = dup2(file, 1); // uses lowest number descriptor (1, since just
// closed stdout)
close(file); // closes old file descriptor duplicate, close() uses int
myargc = myargc-2;
}
}
if ((pid = fork()) == -1 )
{
// if fork fails, print error and exit
perror("Fork failed");
exit(-1);
}
else if (pid == 0) { // child process
if (read == 0 && write == 0)
{
printf("This is the child ready to execute: ");
fflush(stdout);
for (i =0; i < myargc; i++)
{
printf("%s ", myargv[i]);
fflush(stdout);
}
printf("\n");
}
if (execvp(*myargv,myargv) < 0);
{
printf("Execution failed.");
}/* error exit - exec returned */
close(newfile);
dup2(stdout2, STDIN_FILENO);
//close(file);
//if (close(file) == 0)
//{
//dup2(newfile, STDOUT_FILENO);
//close(newfile);
//close(stdout2);
// printf("Reopened stdout\n");
// }
perror("Exec returned");
exit(-1);
}
close(newfile);
if (background == 1) { /* this is the parent -- wait for child to terminate */
wait(pid,0,0);
printf("The parent is exiting now\n");
}else{
waitpid(pid, NULL, WNOHANG); //returns immediately, no wait
}
//test for correct parsing
printf("myargv:\n");
for (i = 0; i < myargc; i++)
{
printf("%s\n", myargv[i]);
}
printf("myargc: %d\n", myargc);
// clear out buffers
memset(&myargv[0], 0, sizeof(myargv));
memset(&input[0], 0, sizeof(input));
}
}

Resources