Related
I'm writing a simple shell in C and encountered a minor problem.
I have the following function:
int execStdErr(char** parsedArguments, int numberOfArgs) {
fflush(stderr);
int fd;
int parsedCommandLength = 0;
char** parsedCommand = parseLine(parsedArguments[0], &parsedCommandLength);
parsedArguments[numberOfArgs - 1] = deleteSpaces(parsedArguments[numberOfArgs - 1]);
if (fork() == 0) {
if (fd = open(parsedArguments[numberOfArgs - 1], O_WRONLY | O_CREAT |O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
perror("lsh");
return 1;
}
if (dup2(fd, 2) < 0) {
perror("lsh") ;
return 1;
}
close(fd);
execvp(parsedCommand[0], parsedCommand);
exit(0);
}
close(fd);
wait(NULL);
return 0;
}
parsedArguments are arguments splitted by 2>, then I take the last one as it is name of my file, and I process the previous one by splitting them on spaces (and they are in parsedCommand). For some reason the stderr prints on screen, it creates a file if it didn't exist but it is always empty. I don't know what might be the problem here.
A common error:
if (fd = open(...) < 0)
is equivalent to
if (fd = (open(...) < 0))
which is not what you want. You need:
if ( (fd = open(...)) < 0)
When open succeeds, open(...) < 0 evaluates to false and fd = open(...) < 0 assigns 0 to fd. The value returned by open, however, is lost.
I am trying to read a file by the parent process, send the content to two child processes and child processes write content to a shared memory segment. However, at each run, I get different outputs and I cannot figure out why.
I use two named pipes and after writing to shared memory, the parent process opens the shared memory and reads the content of each memory.
The first child writes to memory as it gets but the second child converts to hexadecimal.
Here is my main function; assume that stringtohex() works correctly.
int main()
{
pid_t pid_1, pid_2;
int fd, sd; // pipes
const int SIZE = 4096;
const char infile[] = "in.txt";
FILE *tp; // file pointers
pid_1 = fork();
if (pid_1 < 0)
{
fprintf(stderr, "Fork 1 failed");
return(1);
}
if (pid_1 > 0)
{
pid_2 = fork();
if (pid_2 < 0)
{
fprintf(stderr, "Fork 2 failed");
return(1);
}
if (pid_2 > 0) // parent
{
tp = fopen(infile, "r");
if (tp == 0)
{
fprintf(stderr, "Failed to open %s for reading", infile);
return(1);
}
mknod(PIPE_NAME_1, S_IFIFO | 0666, 0);
mknod(PIPE_NAME_2, S_IFIFO | 0666, 0);
fd = open(PIPE_NAME_1, O_WRONLY);
sd = open(PIPE_NAME_2, O_WRONLY);
if (fd > 0 && sd > 0)
{
char line[300];
while (fgets(line, sizeof(line), tp))
{
int len = strlen(line);
int num_1 = write(fd, line, len);
int num_2 = write(sd, line, len);
if (num_1 != len || num_2 != len)
perror("write");
else
printf("Ch 1: wrote %d bytes\n", num_1);
printf("Ch 2: wrote %d bytes\n", num_2);
}
close(fd);
close(sd);
}
fclose(tp);
wait(NULL);
int shm_fd = shm_open("Ch_1", O_RDONLY, 0666);
if (shm_fd == -1)
{
fprintf(stderr, "Failed: Shared Memory 1");
exit(-1);
}
int shm_sd = shm_open("Ch_2", O_RDONLY, 0666);
if (shm_sd == -1)
{
fprintf(stderr, "Failed: Shared Memory 2");
exit(-1);
}
void *ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED)
{
printf("Map failed 1\n");
return -1;
}
void *ptr2 = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_sd, 0);
if (ptr2 == MAP_FAILED)
{
printf("Map failed 2\n");
return -1;
}
fprintf(stdout, "Normal input: \n%s\n", ptr);
fprintf(stderr, "Hexadecimal: \n%s\n", ptr2);
}
else // second child
{
// open shared memory segment
int shm_child_2 = shm_open("Ch_2", O_CREAT | O_RDWR, 0666);
// configure the size of the shared memory segment
ftruncate(shm_child_2, SIZE);
// map the pointer to the segment
void *ptr_child_2 = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_child_2, 0);
if (ptr_child_2 == MAP_FAILED)
{
printf("Map failed 3\n");
return -1;
}
// configure named pipe
mknod(PIPE_NAME_2, S_IFIFO | 0666, 0);
sd = open(PIPE_NAME_2, O_RDONLY);
if (sd > 0) // reading from pipe
{
int num;
char s[300];
while ((num = read(sd, s, sizeof(s))) > 0)
{
// convert to hexadecimal
char hex[strlen(s) * 2 + 1];
stringtohex(s, hex);
// write into segment
sprintf(ptr_child_2, "%s", hex);
ptr_child_2 += strlen(s) * 2;
}
close(sd);
}
exit(0);
}
}
else // first child
{
// create shared memory segment
int shm_child_1 = shm_open("Ch_1", O_CREAT | O_RDWR, 0666);
// configure the size of the shared memory segment
ftruncate(shm_child_1, SIZE);
// map the pointer to the segment
void *ptr_child_1 = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_child_1, 0);
if (ptr_child_1 == MAP_FAILED)
{
printf("Map failed 4\n");
return -1;
}
// configure named pipe
mknod(PIPE_NAME_1, S_IFIFO | 0666, 0);
fd = open(PIPE_NAME_1, O_RDONLY);
if (fd > 0) // reading from pipe
{
int num;
char s[300];
while ((num = read(fd, s, strlen(s))) > 0)
{
// write into segment
sprintf(ptr_child_1, "%s", s);
ptr_child_1 += strlen(s);
}
close(fd);
}
exit(0);
}
return 0;
}
For example input file has:
Harun
sasmaz
59900
1234
Aaaa
Results are:
Normal input:
HARUN
sasmaz
59900
1234
Aaaa4
Hexadecimal:
484152554E0A7361736D617A0A35393930300A313233340A41616161
or
Normal input:
HARUN
sasmaz
asmaz59900
1234
Aaaa
Hexadecimal:
484152554E0A7361736D617A0A35393930300A0A313233340A41616161FF03
I've been trying to do c programming implementation of cp command in unix/linux by using system calls (read(), write(), open(), close()).
But when I run my program through terminal by copying my source code of this program to the same directory with name change (the source code is about 300 lines)
and when I open that output file , it has more character than the original file.
The extra line is the same as 200ish line. Where does it came from?
here's the screenshot when compile
argp.c
123.c
This is the source code near the end of the original file(argp.c). You will see how I use the read write method.
while (count - ind > 1) {
strcpy(cdir, argv[argc-1]);
if (!isFile(cdir)) {
strcat(cdir, basename(arguments.argv[ind]));
}
if (arguments.update) {
stat(cdir,&stDest);
stat(arguments.argv[ind],&stSrc);
if (difftime(stDest.st_mtim.tv_sec, stSrc.st_mtim.tv_sec) > 0 ) {
printf("Destination file is newer\n");
exit(EXIT_FAILURE);
}
}
//open source file
src = open(arguments.argv[ind],O_RDONLY);
//if source file can't be opened
if (src == -1) {
printf("\nError opening file %s errno = %d\n",arguments.argv[ind],errno);
exit(EXIT_FAILURE);
}
//open target file
if (arguments.force) {
//with -f option(default)
tgt = open(cdir, O_WRONLY | O_CREAT | O_TRUNC , S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IWGRP | S_IWOTH);
} else {
//with -n option
tgt = open(cdir, O_WRONLY | O_CREAT | O_EXCL , S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IWGRP | S_IWOTH);
}
//if the target file cannot be read or already exist(with -n option)
if (tgt == -1) {
printf("File exist or it's not a file.\nCan't copy.\n");
exit(EXIT_FAILURE);
}
//read source file
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, BUFFERSIZE) != pos) {
exit(EXIT_FAILURE);
}
}
//if the source file cannot be read
if (pos == -1) {
printf("\nError in reading data from %s\n",arguments.argv[ind]);
}
//close source file
if (close(src) == -1) {
printf("\nError in closing file %s\n",arguments.argv[ind]);
}
//close target file
if (close(tgt) == -1) {
printf("\nError in closing file %s\n",cdir);
}
ind++;
}
if (arguments.verbose) {
printf("Copy successfully!\n");
}
exit(EXIT_SUCCESS);
}
This is the source code near the end of the copy file(123.c)
while (count - ind > 1) {
strcpy(cdir, argv[argc-1]);
if (!isFile(cdir)) {
strcat(cdir, basename(arguments.argv[ind]));
}
if (arguments.update) {
stat(cdir,&stDest);
stat(arguments.argv[ind],&stSrc);
if (difftime(stDest.st_mtim.tv_sec, stSrc.st_mtim.tv_sec) > 0 ) {
printf("Destination file is newer\n");
exit(EXIT_FAILURE);
}
}
//open source file
src = open(arguments.argv[ind],O_RDONLY);
//if source file can't be opened
if (src == -1) {
printf("\nError opening file %s errno = %d\n",arguments.argv[ind],errno);
exit(EXIT_FAILURE);
}
//open target file
if (arguments.force) {
//with -f option(default)
tgt = open(cdir, O_WRONLY | O_CREAT | O_TRUNC , S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IWGRP | S_IWOTH);
} else {
//with -n option
tgt = open(cdir, O_WRONLY | O_CREAT | O_EXCL , S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR | S_IWGRP | S_IWOTH);
}
//if the target file cannot be read or already exist(with -n option)
if (tgt == -1) {
printf("File exist or it's not a file.\nCan't copy.\n");
exit(EXIT_FAILURE);
}
//read source file
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, BUFFERSIZE) != pos) {
exit(EXIT_FAILURE);
}
}
//if the source file cannot be read
if (pos == -1) {
printf("\nError in reading data from %s\n",arguments.argv[ind]);
}
//close source file
if (close(src) == -1) {
printf("\nError in closing file %s\n",arguments.argv[ind]);
}
//close target file
if (close(tgt) == -1) {
printf("\nError in closing file %s\n",cdir);
}
ind++;
}
if (arguments.verbose) {
printf("Copy successfully!\n");
}
exit(EXIT_SUCCESS);
}
it(EXIT_FAILURE);
}
//read source file
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, BUFFERSIZE) != pos) {
exit(EXIT_FAILURE);
}
}
//if the source file cannot be read
if (pos == -1) {
printf("\nError in reading data from %s\n",arguments.argv[ind]);
}
//close source file
if (close(src) == -1) {
printf("\nError in closing file %s\n",arguments.argv[ind]);
}
//close target file
if (close(tgt) == -1) {
printf("\nError in closing file %s\n",cdir);
}
ind++;
}
if (arguments.verbose) {
printf("Copy successfully!\n");
}
exit(EXIT_SUCCESS);
}
You always try to read/write BUFFERSIZE bytes. But what happens if the file you want to copy has a size multiple of BUFFERSIZE? You write what have been read last time.
read return the number of bytes read, so each write should try to write this number of bytes:
Instead of:
pos = read(src, buffer, BUFFERSIZE);
//write target file
while (pos > 0) {
write(tgt, buffer, BUFFERSIZE);
pos = read(src, buffer, BUFFERSIZE);
}
Use:
pos = read(src, buffer, BUFFERSIZE);
//write target file
while (pos > 0) {
write(tgt, buffer, pos);
pos = read(src, buffer, BUFFERSIZE);
}
Same here, instead of:
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, BUFFERSIZE) != pos) {
exit(EXIT_FAILURE);
}
}
Use:
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, pos) != pos) {
exit(EXIT_FAILURE);
}
}
You unconditionally write a full buffer, regardless of how much was read:
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, BUFFERSIZE) != pos) {
exit(EXIT_FAILURE);
}
}
should be:
//write target file
while ((pos = read(src, buffer, BUFFERSIZE)) > 0) {
if (write(tgt, buffer, pos) != pos) {
exit(EXIT_FAILURE);
}
}
So I was following a little outdated book (2010) and I'm trying to copy a file with Linux system calls. This is what i have:
NOTE: Ignore the tlpi_hdr.h and error_functions.h, they define errExit() and fatal() and some otheres, they just print the error and exit.
#include <stdio.h>
#include <fcntl.h>
#include "lib/tlpi_hdr.h"
#include "lib/error_functions.h"
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
int main(int argc, char *argv[])
{
int inputFd, outputFd, openFlags;
mode_t filePerms;
ssize_t numRead;
char buf[BUF_SIZE];
if (argc != 3 || strcmp(argv[1], "--help") == 0) {
usageErr("%s old-file new-file\n", argv[0]);
}
inputFd = open(argv[1], O_RDONLY);
if (inputFd == -1) {
errExit("Opening file %s", argv[1]);
}
openFlags = O_CREAT | O_WRONLY | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
outputFd = open(argv[2], openFlags, filePerms);
if (outputFd == -1) {
errExit("Opening file for writing %s", argv[1]);
}
while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0) {
if (write(outputFd, buf, numRead) != numRead))
fatal("I/O Error");
if (numRead == -1)
fatal("Reading error");
}
if (close(outputFd == -1))
errExit("close input");
if (close(inputFd == -1))
errExit("close output");
return EXIT_SUCCESS;
}
I'm failing on closing of the output file descriptor with EBADF Bad file descriptor:
thinkpad :: ~/.tlpi % ./cp.o a b
ERROR [EBADF Bad file descriptor] close output
The file copies fine tho:
thinkpad :: ~/.tlpi % sha1sum a
40a925a93e149ac53d2630cde8adeb63b8134b29 a
thinkpad :: ~/.tlpi % sha1sum b
40a925a93e149ac53d2630cde8adeb63b8134b29 b
thinkpad :: ~/.tlpi %
Why?
Let's take a closer look at your close call:
close(outputFd == -1)
Here you are comparing outputFd to the value -1. The result of that is a boolean value, which in C will be either 0 or 1. This happens to be either standard input or standard output, depending on the result. Not a file you descriptor you should close.
My guess is that you meant
if (close(outputFd) == -1)
I'm trying to read a file using file descriptors (which is probably a lot more work than I need to do, but nonetheless..)
I'm trying to create an archiver similar to ar. I have a non empty file I'm trying to read from but when I try the read command to retrieve the first 8 bytes the return int is 0 which means it didn't read any bytes. And errno tells me everything went fine.
What I'm trying to do is read the string at the beginning of the file so I may run string comparisons.
Sorry about the spaghetti code, I'm still testing and trying to figure things out.
The problem is at the statement temp = read(archiveFD,buf,8); archiveFD points to my archive file, which is non empty but nothing is read.
command:
./a.out r ar.c archive.a
ar.c:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <utime.h>
#include <errno.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int fileFD, archiveFD, openFlags;
mode_t filePerms;
ssize_t numRead;
char buf[BUF_SIZE];
char fileName[16];
const struct utimbuf *times;
char modTime[12];
char entry[29];
int temp;
char *line = NULL;
size_t len = 0;
if(strcmp(argv[1], "r") != 0 && strcmp(argv[1], "x") != 0 && strcmp(argv[1], "d") != 0 && strcmp(argv[1], "t") != 0) {
printf("%s","Not a valid command.\n");
return 0;
}
if(strcmp(argv[1], "r") == 0) {
if(argv[3] == NULL) {
printf("%s","Missing arguments.\n");
return 0;
}
fileFD = open(argv[2], O_RDONLY);
if(fileFD == -1) {
printf("%s","Error opening input file.\n");
return 0;
}
openFlags = O_CREAT | O_RDWR | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
archiveFD = open(argv[3], openFlags, filePerms);
if(archiveFD == -1) {
printf("%s","Error opening archive file.\n");
return 0;
}
temp = read(archiveFD,buf,8);
//printf("%s",(char *) buf);
// if(strcmp("!<arch>\n",buf) != 0)
// write(archiveFD,"!<arch>\n",8); //begins archive
// printf("%s","here");
//}
printf("%d",temp);
printf("%s",strerror(errno));
//printf("%s",buf);
sprintf(fileName,"%-16s",argv[2]);
printf("%s",fileName);
utime(argv[2],times);
//strcpy(modTime,"12345678901234");
//printf("%s",modTime);
sprintf(modTime,"%-.12lld",(long long) times->modtime);
modTime[12] = '\0';
printf("%s",modTime);
sprintf(entry,"%s%s\n",fileName,modTime);
printf("%s",entry);
write(archiveFD,entry,29);
while((numRead = read(fileFD, buf, BUF_SIZE)) > 0)
if(write(archiveFD, buf, numRead) != numRead) {
printf("%s","Could not write whole buffer.\n");
return 0;
}
if(numRead == -1) {
printf("%s","Error reading.\n");
return 0;
}
if(close(fileFD) == -1) {
printf("%s","Error closing input file.\n");
return 0;
}
if(close(archiveFD) == -1) {
printf("%s","Error closing archive file.\n");
return 0;
}
}
return 0;
}`
archive.a:
ar.c 140737161196
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <utime.h>
#include <errno.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int fileFD, archiveFD, openFlags;
mode_t filePerms;
ssize_t numRead;
char buf[BUF_SIZE];
char fileName[16];
const struct utimbuf *times;
char modTime[12];
char entry[29];
int temp;
char *line = NULL;
size_t len = 0;
if(strcmp(argv[1], "r") != 0 && strcmp(argv[1], "x") != 0 && strcmp(argv[1], "d") != 0 && strcmp(argv[1], "t") != 0) {
printf("%s","Not a valid command.\n");
return 0;
}
if(strcmp(argv[1], "r") == 0) {
if(argv[3] == NULL) {
printf("%s","Missing arguments.\n");
return 0;
}
fileFD = open(argv[2], O_RDONLY);
if(fileFD == -1) {
printf("%s","Error opening input file.\n");
return 0;
}
openFlags = O_CREAT | O_RDWR | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
archiveFD = open(argv[3], openFlags, filePerms);
if(archiveFD == -1) {
printf("%s","Error opening archive file.\n");
return 0;
}
temp = read(archiveFD,buf,8);
//printf("%s",(char *) buf);
// if(strcmp("!<arch>\n",buf) != 0)
// write(archiveFD,"!<arch>\n",8); //begins archive
// printf("%s","here");
//}
printf("%d",temp);
printf("%s",strerror(errno));
//printf("%s",buf);
sprintf(fileName,"%-16s",argv[2]);
printf("%s",fileName);
utime(argv[2],times);
//strcpy(modTime,"12345678901234");
//printf("%s",modTime);
sprintf(modTime,"%-.12lld",(long long) times->modtime);
modTime[12] = '\0';
printf("%s",modTime);
sprintf(entry,"%s%s\n",fileName,modTime);
printf("%s",entry);
write(archiveFD,entry,29);
while((numRead = read(fileFD, buf, BUF_SIZE)) > 0)
if(write(archiveFD, buf, numRead) != numRead) {
printf("%s","Could not write whole buffer.\n");
return 0;
}
if(numRead == -1) {
printf("%s","Error reading.\n");
return 0;
}
if(close(fileFD) == -1) {
printf("%s","Error closing input file.\n");
return 0;
}
if(close(archiveFD) == -1) {
printf("%s","Error closing archive file.\n");
return 0;
}
}
return 0;
}
In this block: (error checking omitted for brevity)
openFlags = O_CREAT | O_RDWR | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
archiveFD = open(argv[3], openFlags, filePerms);
temp = read(archiveFD,buf,8);
I would absolutely expect read to return zero. You just opened the file with O_TRUNC,
so even if the file wasn't empty, it is after you open it. If you do not want to discard all existing data, remove O_TRUNC from openFlags.