I have a program that takes two files as an argument. The first file is to be copied into the second. The program forks into 2 children, the first child reads file and throws it thru the pipe to the other, then the other child writes it out to a file. The two files are supposed to be identical in the end.
When I run diff to compare the two files I get the following error:
virtual#ubuntu:~/Documents/OSprojects$ ./parent test.txt test2.txt
virtual#ubuntu:~/Documents/OSprojects$ cat test.txt
123456789112233445566778899
virtual#ubuntu:~/Documents/OSprojects$ cat test2.txt
123456789112233445566778899
virtual#ubuntu:~/Documents/OSprojects$ diff test.txt test2.txt
Binary files test.txt and test2.txt differ
virtual#ubuntu:~/Documents/OSprojects$
As you can see they are both the same, but the diff prints out that they are different. Obviously its just something I don't understand about the diff cmd. Any help would be appreciated.
I believe for some reason the file I create is a binary file whereas the first file is not, but I am unaware as to why it is a binary file. I believe it might have to do with this line of code:
write(1, buf, BUF_SIZE); //write to buffer
memset(buf, '\0', BUF_SIZE);
In one of the children this is writing out to the buffer then I am clearing the buffer. Am I clearing out that buffer wrong?
Here is the result of cat -e:
virtual#ubuntu:~/Documents/OSprojects$ cat -e test2.txt
123456789112233445566778899$
^#^#^#^#virtual#ubuntu:~/Documents/OSprojects$
Here is the result of cmp:
virtual#ubuntu:~/Documents/OSprojects$ cmp test.txt test2.txt
cmp: EOF on test.txt
virtual#ubuntu:~/Documents/OSprojects$
I believe that is my problem, how can I clear out that buffer so it doesn't throw those at the end?
ALL OF MY CODE::
Parent:
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_SIZE 16
void exitWithError(char* errorMsg, int exitWith); //generic error out function
void launch_writer(const char* pathname, char* const argv[], int pfd[]);
void launch_reader(const char* pathname, char* const argv[], int pfd[]);
int main(int argc, char* argv[]){
//making the pipe
int pfd[2];
if(pipe(pfd) == -1) //test pipe creation
exitWithError("PIPE FAILED", 1);
//forking
pid_t reader_child_pid;
pid_t writer_child_pid;
//args for each fork
char *args_1[] = {"reader", argv[1], (char *) 0};
char *args_2[] = {"writer", argv[2], (char *) 0};
if((writer_child_pid = fork()) == -1) {
exitWithError("WRITER FORK FAILED", 1);
}
else if (writer_child_pid == 0) { //first child comes here
launch_writer("./writer", args_2, pfd);
}
else if ((reader_child_pid = fork()) == -1) {
exitWithError("READER FORK FAILED", 1);
}
else if (reader_child_pid == 0) { //second child comes here
launch_reader("./reader", args_1, pfd);
}
//parent picks up here
//close off pipe from parents end
close(pfd[0]);
close(pfd[1]);
//wait for all processes to exit before ending
for(;;) {
if(wait(NULL) == -1){
if(errno == ECHILD)
exit(0);
else {
exitWithError("WAIT ERROR", 1);
}
}
}
}
void exitWithError(char* errorMsg, int exitWith) {
perror(errorMsg);
exit(exitWith);
}
void launch_writer(const char* pathname, char* const argv[], int pfd[]) {
dup2(pfd[0], 0);
close(pfd[1]);
close(pfd[0]);
execve(pathname, argv, NULL);
perror("execve failed");
}
void launch_reader(const char* pathname, char* const argv[], int pfd[]) {
dup2(pfd[1], 1);
close(pfd[1]);
close(pfd[0]);
execve(pathname, argv, NULL);
perror("execve failed");
}
Child 1:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 16
int main(int argc, char* argv[]){
//Opens file to be read from
int inFile = open(argv[1], O_RDONLY);
//declaring variables
char buf[BUF_SIZE]; //temp hold whats read/written
int read_test; //check if EOF
for(;;) {
read_test = read(inFile, buf, BUF_SIZE); //read from file
if(read_test == 0) //eof
break;
write(1, buf, BUF_SIZE); //write to buffer
memset(buf, '\0', BUF_SIZE);
}
close(inFile);
exit(0);
}
Child 2:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUF_SIZE 16
int main(int argc, char* argv[]){
//Opens a file for reading/writing, if exists then truncates, otherwise makes new one
//with correct permissions
int wri_inFile = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC , S_IRUSR | S_IWUSR);
if(wri_inFile == -1)
perror("ERROR OPENING FILE");
//declaring variables
char buf[BUF_SIZE]; //to store what is read in/written out
int read_test; //test if EOF
for(;;) {
read_test = read(0, buf, BUF_SIZE); //read from buffer
if(read_test == 0) //eof
break;
write(wri_inFile, buf, BUF_SIZE); //write to file
}
close(wri_inFile);
exit(0);
}
You don't check (and use) the read data length. Therefore, your data gets padded with garbage.
There should be actual data bytes read (read_test):
read_test = read(0, buf, BUF_SIZE); //read from buffer
if(read_test == 0) //eof
break;
write(wri_inFile, buf, BUF_SIZE); //write to file
-----------------------^^^^^^^^
The same applies to the other child. You should also check the error conditions.
Related
The following program implements a shell (simplified). I have a problem: when I redirect stdout to a file, the$symbols appear at the end of the file. What edits do I need to do to stop appearing?
I also have a problem running the exit command: it does not exit the program. How can I solve it?
The shell reads the commands and tries to execute them.
code:
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
char *
getinput(char *buffer, size_t buflen) {
printf("$$ ");
return fgets(buffer, buflen, stdin);
}
int
main(int argc, char **argv) {
char buf[BUFSIZ];
pid_t pid;
int status;
(void)argc;
(void)argv;
while (getinput(buf, sizeof(buf))) {
buf[strlen(buf) - 1] = '\0';
if((pid=fork()) == -1) {
fprintf(stderr, "shell: can't fork: %s\n",
strerror(errno));
continue;
} else if (pid == 0) { /* child */
execlp(buf, buf, (char *)0);
fprintf(stderr, "shell: couldn't exec %s: %s\n", buf,
strerror(errno));
exit(EX_UNAVAILABLE);
}
/* parent waits */
if ((pid=waitpid(pid, &status, 0)) < 0) {
fprintf(stderr, "shell: waitpid error: %s\n",
strerror(errno));
}
}
exit(EX_OK);
}
I also have a problem running the exit command: it does not exit the program. How can I solve it?
the terminal looks like this:
mike#ubuntu:~process/homework$ echo "foobar" > input
mike#ubuntu:~process/homework$ cat output`
$$ $$ $$ mike#ubuntu:~process/homework$ ./shell < input > output 2 > err
mike#ubuntu:~process/homework$ cat output
$$ $$ $$ mike#ubuntu:~process/homework$ cat err
shell: couldn't exec foobar: No such file or directory
exit is a shell builtin, and should be handled before any forking occurs.
Use isatty(3) to determine if stdout refers to a terminal, and only print your prompt if it does.
Here is a basic example, but do note that a real exit command supports a single numerical argument, which becomes the exit status of the shell, otherwise the exit status is that of the last command executed.
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
char *
getinput(char *buffer, size_t buflen) {
if (isatty(STDOUT_FILENO))
printf("$$ ");
return fgets(buffer, buflen, stdin);
}
int
main(int argc, char **argv) {
char buf[BUFSIZ];
pid_t pid;
int status = EXIT_SUCCESS;
(void)argc;
(void)argv;
while (getinput(buf, sizeof(buf))) {
buf[strlen(buf) - 1] = '\0';
if (0 == strcmp(buf, "exit"))
exit(WEXITSTATUS(status));
if((pid=fork()) == -1) {
fprintf(stderr, "shell: can't fork: %s\n",
strerror(errno));
continue;
} else if (pid == 0) { /* child */
execlp(buf, buf, (char *)0);
fprintf(stderr, "shell: couldn't exec %s: %s\n", buf,
strerror(errno));
exit(EX_UNAVAILABLE);
}
/* parent waits */
if ((pid=waitpid(pid, &status, 0)) < 0) {
fprintf(stderr, "shell: waitpid error: %s\n",
strerror(errno));
}
}
exit(EX_OK);
}
I tried to make a copy program. I made it, but it's hard to implement copying time-atrributes(access time, modify time, change time).
I thought that I can make it using st_atime, st_mtime, st_ctime of struct stat.
But I don't know where should I use them.
Can you help me?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#define MAX_BUF 64
int main(int argc, char *argv[]) {
char buf[MAX_BUF];
int fd, fd1, read_size, write_size;
struct stat stat; // struct stat variable
// if the number of arguments are not 3, return 0
if(argc != 3) {
printf("\nUSAGE: %s [old_file_name] [new_file_name]\n\n", argv[0]);
return 0;
}
fd = open(argv[1], O_RDONLY); // execute an original file descriptor(read only)
fstat(fd, &stat); // store stats of the original file
// execute a file descripoter to be copied
if(0 < (fd1 = open(argv[2], O_RDWR | O_CREAT | O_EXCL, stat.st_mode))) {
// write data of original in copied
while(1) {
read_size = read(fd, buf, MAX_BUF);
if(read_size == 0) break;
write_size = write(fd1, buf, read_size);
}
} else
printf("\nfile name of [%s] is already exist\n\n", argv[2]);
close(fd);
close(fd1); // close file descriptors
}
The function you're after is called utime().
I am trying to write a C program which uses standard I/O and System calls to perform copying of contents of one file to another file.
So far, I have done this :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd1, fd2;
char buffer[1024];
long int n1;
if(((fd1 = open(argv[1], O_RDONLY)) == -1) || ((fd2=open(argv[2],O_CREAT|O_WRONLY|O_TRUNC, 0700)) == -1)){
perror("file problem");
exit(1);
}
while((n1=read(fd1, buffer, 1024) > 0)){
if(write(fd2, buffer, n1) != n1){
perror("writing problem ");
exit(3);
}
}
close(fd1);
close(fd2);
}
When I run the program like this :
cc copyContents.c
./a.out one.txt two.txt
Assuming that one.txt is well defined, what I want is to create a new file called two.txt and copy over all the contents of one.txt
When I look into the contents of two.txt after running the program, it has literally nothing in it. Just a blank file.
Where am I going wrong?
You wrote
while((n1=read(fd1, buffer, 1024) > 0)){
instead of
while ( (n1 = read(fd1, buffer, 1024)) > 0)
In your code the code int the while condition boils down to:
n1 = (read(fd1, buffer, 1024) > 0)
So the read is done correctly, it's return value is compared to 0, the result of the comparision (0 or 1) is assigned to n1.
This shows once more how important it is to format your code in a way that makes it readable.
You could have debugged this easily yourself with a debugger or by inserting one or two printfs in your code.
Input:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
void typefile (char *filename)
{
int fd, nread;
char buf[1024];
fd = open (filename, O_RDONLY);
if (fd == -1) {
perror (filename);
return;
}
while ((nread = read (fd, buf, sizeof (buf))) > 0)
write (1, buf, nread);
close (fd);
}
int main (int argc, char **argv)
{
int argno;
for (argno = 1; argno < argc; argno )
typefile (argv[argno]);
exit (0);
}
Output:
student#ubuntu:~$gcc –o prg10.out prg10.c
student#ubuntu:~$cat > ff
hello`enter code here`
hai
student#ubuntu:~$./prg10.out ff
hello
hai
This is the best solution and easily executable.
input:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int f1, f2;
char buff[50];
long int n;
if(((f1 = open(argv[1], O_RDONLY)) == -1 || ((f2=open(argv[2], O_CREAT |
O_WRONLY | O_TRUNC, 0700))== 1)))
{
perror("problem in file");
exit(1);
}
while((n=read(f1, buff, 50))>0)
if(write(f2, buff, n)!=n)
{
perror("problem in writing");
exit(3);
}
if(n==-1)
{
perror("problem in reading");
exit(2);
}
close(f2);
exit(0);
}
Output:
cc sys.c
./a.out a.txt b.txt
cat b.txt
So, a.txt should have some content and this content is copied to b.txt
by "cat b.txt" you can cross-check the content(which is in "a.txt").
Narenda checks if n==-1 inside the loop, but, the loop test is n>0, so, that'll never happen.
Also, the test for a bad read should precede the attempt to write.
I'm trying to create two-way communication between parent and child processes using 2 pipes in C.the prog1 running in child1
I want to read 3+4+5 from prog1 after that send something to prog1 with write but I could not.
Where is the wrong?
/* prog1.c */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void
main(void){
int FD;
unsigned int buf;
char buf[15];
printf("7+5+11=?\n");
FD=read(0,buf,10);
if(FD<0){
perror("FAIL\n");
exit(EXIT_FAILURE);
}
printf("TAKED:%s\n",buf);
}
prog2.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
void ERR_SYS(const char *msg);
int
main(void){
char buf[15];
int pipe1[2];
int pipe2[2];
pid_t childpid;
memset(buf,'\0',14);
if(pipe(pipe1) < 0 || pipe(pipe2) < 0)
ERR_SYS("fail_pipe");
if((childpid = fork()) < 0)
ERR_SYS("fail_fork");
if(childpid==0)
{
dup2(pipe2[1],1);
dup2(pipe1[0],0);
close(pipe1[1]);
close(pipe2[0]);
close(pipe2[1]);
close(pipe1[0]);
//close(1);
//close(0);
execle("./prog1",NULL,NULL,NULL);
}else{
close(pipe1[0]);
close(pipe2[1]);
read(pipe2[0],buf,4); /*I hope to read 3+4+5*/
printf("BuF::%s\n",buf);
write(pipe1[1],"off",3);/*send {off}*/
wait(NULL);
}
return 0;
}
void
ERR_SYS(const char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
There are few problems with your program:
You are not checking returned values of read, write and execle in prog2.c
You are sending "7+5+11=?\n" string which is 10 characters long but only expecting 4 characters ( 3+4+5 is not even four characters ).
Also "off" you are sending is 3 characters long but without including null termination.
When you read from an fd you will in both cases not get null terminated string and then you are trying to printf it. It's a quick way to undefined behaviour. Put an '\0' after the end of buffer you read from any file descriptor!
Especially what read returns is very important as it tells you how many characters were read. You should never ignore returned value of read (in some cases it's the same with write function).
Next time also provide some output of your program as it will be easier to give some help.
I didn't follow all your logic in setting up the pipes, so I modified and hopefully clarified your original. I should note that for whatever reason I named fd_in and fd_out from the external program's (prog1) point of view (e.g. fd_out is where prog1 is writing to, fd_in is where prog1 is reading from).
Here's the contents of my prog3.c:
...
#define READ_END 0
#define WRITE_END 1
void ERR_SYS(const char *msg);
int main(void) {
char buff[15];
char *msg = "hello";
int fd_out[2];
int fd_in[2];
int nbytes;
pid_t childpid;
if(pipe(fd_out) < 0 || pipe(fd_in) < 0) {
ERR_SYS("fail_pipe");
}
if((childpid = fork()) < 0) {
ERR_SYS("fail_fork");
}
if(childpid==0) { //child
//connect the write end of fd_out to stdout
dup2(fd_out[WRITE_END], STDOUT_FILENO);
close(fd_out[WRITE_END]);
//connect the read end of fd_in to stdin
dup2(fd_in[READ_END], STDIN_FILENO);
close(fd_in[READ_END]);
//the exec'd prog1 will inherit the streams
execlp("./prog1", "prog1", NULL); //TODO: check return
} else { //parent
nbytes = write(fd_in[WRITE_END], msg, strlen(msg));
//TODO: handle any errors from write
nbytes = read(fd_out[READ_END],buff,sizeof(buff)-1);
//TODO: handle any errors from read
buff[nbytes] = '\0';
printf("contents of buff::%s",buff);
}
return 0;
}
void ERR_SYS(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
And here's the contents of my prog1.c
int main(void){
char buff[15];
int nbytes;
nbytes = read(STDIN_FILENO, buff, sizeof(buff)-1);
buff[nbytes] = '\0';
printf("%s world\n", buff);
return 0;
}
I am trying to make this work but no luck, basically i need to write to the pipe and then make the pipe return back with the text i sent. I have a server.c and client.c , so i make the server.c run..., open a new terminal and then run the client.. the problem is that the client doesnt do anything when i run it.. I am sure i am missing something.. like closing the pipe. i am not sure.. I would really appreciate some guidance
server.c
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define PIPE1 "PIPE1"
#define PIPE5 "PIPE5"
#define MAX_BUF_SIZE 255
int main(int argc, char *argv[])
{
int rdfd1,rdfd2,rdfd3,rdfd4, wrfd1,wrfd2,wrfd3,wrfd4,ret_val, count, numread1,numread2,numread3,numread4;
char buf1[MAX_BUF_SIZE];
char buf2[MAX_BUF_SIZE];
char buf3[MAX_BUF_SIZE];
char buf4[MAX_BUF_SIZE];
/* Create the first named - pipe */
ret_val = mkfifo(PIPE1, 0666);
if ((ret_val == -1) && (errno != EEXIST)) {
perror("Error creating the named pipe");
return 1;
}
ret_val = mkfifo(PIPE5, 0666);
if ((ret_val == -1) && (errno != EEXIST)) {
perror("Error creating the named pipe");
return 1;
}
/* Open the first named pipe for reading */
rdfd1 = open(PIPE1, O_RDONLY);
/* Open the first named pipe for writing */
wrfd1 = open(PIPE5, O_WRONLY);
/* Read from the pipes */
numread1 = read(rdfd1, buf1, MAX_BUF_SIZE);
buf1[numread1] = '0';
printf("Server : Read From the pipe : %sn", buf1);
/*
* Write the converted content to
* pipe
*/
write(wrfd1, buf1, strlen(buf1));
}
client.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PIPE1 "PIPE1"
#define PIPE5 "PIPE5"
#define MAX_BUF_SIZE 255
int main(int argc, char *argv[ ]) {
pid_t childpid;
int error;
int i;
int nprocs;
/* check command line for a valid number of processes to generate */
int wrfd1, rdfd1, numread;
char rdbuf[MAX_BUF_SIZE];
if ( (argc != 2) || ((nprocs = atoi (argv[1])) <= 0) ) {
fprintf (stderr, "Usage: %s nprocs\n", argv[0]);
return 1;
}
for (i = 1; i < nprocs; i++) {
/* create the remaining processes */
if ((childpid = fork()) == -1) {
fprintf(stderr, "[%ld]:failed to create child %d: %s\n", (long)getpid(), i, strerror(errno));
return 1;
}
/* Open the first named pipe for writing */
wrfd1 = open(PIPE5, O_WRONLY);
/* Open the second named pipe for reading */
rdfd1 = open(PIPE1, O_RDONLY);
if (childpid)
break;
char string1[100];
if(sprintf(string1, "This is process %d with ID %ld and parent id %ld\n", i, (long)getpid(), (long)getppid())) {
write(wrfd1,string1, strlen(string1));
}
/* Read from the pipe */
numread = read(rdfd1, rdbuf, MAX_BUF_SIZE);
rdbuf[numread] = '0';
printf("Full Duplex Client : Read From the Pipe : %sn", rdbuf);
}
return 0;
}
It seems like both server and client read from PIPE1 and write to PIPE5. Shouldn't one of them write to PIPE1 so that the other can read it from the other end?
Also, if you're testing with ./client 1, your for (i = 1; i < nprocs; i++) loop will never execute.
One last thing, see this question. I'm not entirely sure it applies to your code, but it's worth keeping in mind.
Shouldn't this line be '\0' ?
buf1[numread1] = '0';