LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   system call (https://www.linuxquestions.org/questions/linux-newbie-8/system-call-564971/)

oliviapesayco 06-27-2007 09:31 PM

system call
 
Please tell me what is wrong with this code... There are no errors, it creates the file, but it does not write to the file:

#include<stdio.h>
#include<fcntl.h>

main()
{
char *p = ("hello world");
int fp;

fp = open ("samplex.c", O_CREAT, 0666);
write (fp,p,11);
fork ();
}

bartonski 06-27-2007 11:21 PM

check out man 2 open

Quote:


The parameter flags is one of O_RDONLY, O_WRONLY or O_RDWR which
request opening the file read-only, write-only or read/write, respec-
tively, bitwise-or’d with zero or more of the following:

O_CREAT
...

I compiled and ran the following:

Code:

int main(void)
{
        char *p = ("hello world");
        int fp;

        fp = open ("samplex.c", O_WRONLY | O_CREAT, 0666);
        write (fp,"hello world",11);
        fork ();
        return 0;
}

yielding "hello world" as expected.

PatrickNew 06-27-2007 11:22 PM

probably the lack of a close(). The string "Hello World." is probably short enough that the OS cached the write, but then you never properly closed the string, so the cache may not ever be written to disk. And, out of curiosity, what is the purpose of the fork()?

Regarding bartonski's comment: Umm, oh yeah, that too.

bartonski 06-28-2007 10:39 AM

Quote:

Originally Posted by PatrickNew
probably the lack of a close(). The string "Hello World." is probably short enough that the OS cached the write, but then you never properly closed the string, so the cache may not ever be written to disk.

Quick programmer's trick:

Whenever you have *anything* that can be opened and closed, eg. open and closed braces, malloc/free, fopen/fclose, open and close perens... you get the picture... write both at the same time, then write your code between them. This is guaranteed to save you hours of debugging.

Caveat to the above:

If you have some sort of branch make sure that any resources that you have open get closed regardless of how the conditional turns out.


All times are GMT -5. The time now is 10:05 PM.