I was analyzing the way a C program in Linux writes to a file and I summarize it to:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "restart.h"
#define CREATE_FLAGS (O_WRONLY | O_CREAT | O_APPEND)
#define CREATE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(void) {
int fd;
fd = open("my.file", CREATE_FLAGS, CREATE_MODE);
dup2(fd, STDOUT_FILENO);
r_close(fd) ;
write(STDOUT_FILENO, "Hello World", 11) ;
return 0;
}
the two small header files r_close.c and restart.h are in THIS link.
So my question is I will like to know how the program is writing to the file. For example what is the difference of doing it in c# as:
static void Main(string[] args)
{
var file = System.IO.File.OpenWrite("my.file");
file.Write(System.Text.Encoding.ASCII.GetBytes("Hello World"), 0, 11);
file.Close();
}
I looked at the description of dup2 method in many links such as at http://www.mkssoftware.com/docs/man3/dup2.3.asp and I am having a hard time trying to understand what it basically does.
The call:
is equivalent to:
What this means is that we have modified the table that the OS has to hold the open files descriptor. It uses the
fcntl()function. fcntl() provides control of open file descriptors. Basicly it copies an int to an int. But it does it using a system call; as it modifies an OS resource. Your saying to the system: You know that Index in the FileTable? Yes? well copy the FilePointer to another Index. ( A few other things also but I’ll have to ignore that for now.)Re: the second part of your question, What is the difference?
They basically do the same thing. Probably exactly the same chars are written to the file. It does do one extra thing. That is it
dup2()STDOUT_FILENO. to a file. That changes what the standard output is. If I’m not mistaken that code will redirect all output that would normally go to the console tofd, in your case"my.file". That’s the main difference between the C# and C done you listed.It should also be noted that the whole
dup2()in this sample is kind of pointless if all you are concerned with is to write “Hello World” to a file. It is sorta like goingint x = 5; int y = x; Console.WriteLine(y);. The extra step doesn’t anything in your example.Another, more general difference, is that C# hides a-lot of the low level stuff from you the programmer. While coding in C, you will be able to do lower level file and system manipulation with more ease. The downside is that you have to do more coding of the lower level stuff. While mostly you don’t really care exactly how that stuff happens, rather that it does indeed happen. So often, it’s quicker to code in C# because all the low level stuff is handled nicely for you already. — Sorta off topic point that may help you understand
Finally I will hazard a guess that;
You were analyzing a program that deals with I/O manipulation, rather than ordinary writing to a file. That would explain the
dup2().