Happy Codings - Programming Code Examples

C Programming Code Examples

C > C on Unix Code Examples

Output of one program is input of another program Using Pipes

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/* Output of one program is input of another program Using Pipes */ #include <unistd.h> #include <process.h> /* Pipe the output of program to the input of another. */ int main() { int pipe_fds[2]; int stdin_save, stdout_save; if (pipe(pipe_fds) < 0) return -1; /* Duplicate stdin and stdout so we can restore them later. */ stdin_save = dup(STDIN_FILENO); stdout_save = dup(STDOUT_FILENO); /* Make the write end of the pipe stdout. */ dup2(pipe_fds[1], STDOUT_FILENO); /* Run the program. Its output will be written to the pipe. */ spawnl(P_WAIT, "/dev/env/DJDIR/bin/ls.exe", "ls.exe", NULL); /* Close the write end of the pipe. */ close(pipe_fds[1]); /* Restore stdout. */ dup2(stdout_save, STDOUT_FILENO); /* Make the read end of the pipe stdin. */ dup2(pipe_fds[0], STDIN_FILENO); /* Run another program. Its input will come from the output of the first program. */ spawnl(P_WAIT, "/dev/env/DJDIR/bin/less.exe", "less.exe", "-E", NULL); /* Close the read end of the pipe. */ close(pipe_fds[0]); /* Restore stdin. */ dup2(stdin_save, STDIN_FILENO); return 0; }
dup() Function in C
duplicate an open file descriptor. The dup() system call allocates a new file descriptor that refers to the same open file description as the descriptor oldfd. The new file descriptor number is guaranteed to be the lowest-numbered file descriptor that was unused in the calling process. After a successful return, the old and new file descriptors may be used interchangeably. Since the two file descriptors refer to the same open file description, they share file offset and file status flags; for example, if the file offset is modified by using lseek() on one of the file descriptors, the offset is also changed for the other file descriptor. The two file descriptors do not share file descriptor flags (the close-on-exec flag). The close-on-exec flag (FD_CLOEXEC;) for the duplicate descriptor is off.
Syntax for dup() Function in C
#include <unistd.h> int dup(int fildes);
file descriptor whose copy is to be created. Upon successful completion a non-negative integer, namely the file descriptor, shall be returned; otherwise, -1 shall be returned and errno set to indicate the error. • It uses the lowest-numbered unused descriptor for the new descriptor. • If the copy is successfully created, then the original and copy file descriptors may be used interchangeably. • They both refer to the same open file description and thus share file offset and file status flags. • Include the header file unistd.h for using dup() and dup2() system call. The dup() function shall fail if:
The fildes argument is not a valid open file descriptor.
The number of file descriptors in use by this process would exceed {OPEN_MAX}.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* creates a copy of a file descriptor by dup() function code example */ // program to illustrate dup() #include<stdio.h> #include <unistd.h> #include <fcntl.h> int main() { // open() returns a file descriptor file_desc to a // the file "dup.txt" here" int file_desc = open("dup.txt", O_WRONLY | O_APPEND); if(file_desc < 0) printf("Error opening the file\n"); // dup() will create the copy of file_desc as the copy_desc // then both can be used interchangeably. int copy_desc = dup(file_desc); // write() will write the given string into the file // referred by the file descriptors write(copy_desc,"This will be output to the file named dup.txt\n", 46); write(file_desc,"This will also be output to the file named dup.txt\n", 51); return 0; }
dup2() Function in C
Duplicate a file descriptor, specifying the new descriptor. The dup2() system call is similar to dup() but the basic difference between them is that instead of using the lowest-numbered unused file descriptor, it uses the descriptor number specified by the user. The dup2() system function is used to create a copy of an existing file descriptor.
Syntax for dup2() Function in C
#include <unistd.h> int dup2(int fildes, int fildes2);
The file descriptor that you want to duplicate.
The number that you want to use for the new file descriptor. The dup2() function returns a descriptor with the value fildes2. The descriptor refers to the same file as fildes, and it will close the file that fildes2 was associated with. For more information about the processing which may occur when the file is closed, see close()--Close File or Socket Descriptor. If the original file descriptor was opened in text mode, data conversion is also done on the duplicated file descriptor. The FD_CLOEXEC flag that is associated with the new file descriptor is cleared. Refer to fcntl()--Perform File Control Command for additional information about the FD_CLOEXEC flag. The following conditions apply: • If fildes2 is less than zero or greater than or equal to OPEN_MAX, dup2() returns -1 and sets the errno global variable to [EBADF]. • If fildes is a valid descriptor and is equal to fildes2, dup2() returns fildes2 without closing it. • If fildes is not a valid descriptor, dup2() fails and does not close fildes2. This function works with descriptors for any type of object. dup2() was successful. The value of fildes2 is returned. dup2() was not successful. The errno global variable is set to indicate the error.
The filedes argument isn't a valid open file descriptor, or filedes2 is out of range.
The function was interrupted by a signal.
All file descriptors available to the process are currently open.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* duplicate a file descriptor, specifying the new descriptor by dup2() function code example */ #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <stdlib.h> int main( void ) { int filedes, dup_filedes; filedes = open( "file", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP ); if( filedes != -1 ) { dup_filedes = 4; if( dup2( filedes, dup_filedes ) != -1 ) { /* process file */ /* ... */ close( dup_filedes ); } close( filedes ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
spawnl() Function in C
Spawn a child process, given a list of arguments. spawnl() function loads and executes a new child process. The spawnl() function creates and executes a new child process, named in path with a NULL-terminated list of arguments in arg0 ... argn. This function calls spawnve().
Syntax spawnl() Function in C
#include <process.h> int spawnl( int mode, const char * path, const char * arg0, const char * arg1..., const char * argn, NULL );
How you want to load the child process, and how you want the parent program to behave after the child program is initiated: • P_WAIT: load the child program into available memory, execute it, and make the parent program resume execution after the child process ends. • P_NOWAIT: execute the parent program concurrently with the new child process. • P_NOWAITO: execute the parent program concurrently with the new child process. You can't use wait() to obtain the exit code. • P_OVERLAY: replace the parent program with the child program in memory and execute the child. No return is made to the parent program. This is equivalent to calling the appropriate exec*() function.
The full path name of the executable.
arg0, ... argn, NULL
The arguments that you want to pass to the new process. You must pass at least arg0, which by convention is a pointer to the name of the new child process, and can't be NULL. You must terminate the list with an argument of NULL. If the new child process is a shell script, the first line must start with #!, followed by the path of the program to run to interpret the script, optionally followed by one argument. The script must also be marked as executable. For more information, see "The first line" in the Writing Shell Scripts chapter of the Neutrino User's Guide. The spawnl() function isn't a POSIX 1003.1 function, and isn't guaranteed to behave the same on all operating systems. It builds an argv[ ] array before calling spawn(). Most of the spawn*() functions do a lot of work before a message is sent to procnto. Arguments are passed to the child process by supplying one or more pointers to character strings as arguments. These character strings are concatenated with spaces inserted to separate the arguments to form one argument string for the child process. The child process inherits the parent's environment. The environment is the collection of environment variables whose values that have been defined with the export shell command, the env utility, or by the successful execution of the putenv() or setenv() function. A program may read these values with the getenv() function. A parent/child relationship doesn't imply that the child process dies when the parent process dies. The spawnl() function's return value depends on the mode argument: • P_WAIT: The exit status of the child process. • P_NOWAIT: The process ID of the child process. To get the exit status for a P_NOWAIT process, you must use the waitpid() function, giving it this process ID. • P_NOWAITO: The process ID of the child process, or 0 if the process is being started on a remote node. You can't get the exit status of a P_NOWAITO process. If an error occurs, -1 is returned (errno is set).
The number of bytes used by the argument list of the new child process is greater than ARG_MAX bytes.
Search permission is denied for a directory listed in the path prefix of the new child process or the new child process's file doesn't have the execute bit set.
Insufficient resources available to create the child process.
An error occurred duplicating open file descriptors to the new process.
The mode is P_WAIT, and the spawned process terminated before the call to waitpid() was completed.
One of the buffers specified in the function call is invalid.
The function was interrupted by a signal.
An argument is invalid (e.g. arg0 is NULL, or the value of mode isn't valid).
Too many levels of symbolic links or prefixes.
Insufficient resources available to load the new executable image or to remap file descriptors in the child process.
The length of path exceeds PATH_MAX or a pathname component is longer than NAME_MAX.
The file identified by the path argument is empty, or one or more components of the pathname of the child process don't exist.
The child process's file has the correct permissions, but isn't in the correct format for an executable.
Insufficient memory available to create the child process.
The spawnl() function isn't implemented for the filesystem specified in path.
A component of the path prefix of the child process isn't a directory.
The text file that you're trying to execute is busy (e.g. it might be open for writing).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* spawn a child process, given a list of arguments by spawnl() function code example */ #include <stdio.h> #include <stdlib.h> #include <process.h> // Small app that launches itself using the spanwl function int main(int argc, char *argv[]) { int error; if(argc == 1){ error = spawnl(P_WAIT,"C:\\PROGRAM\\WINDOW~1\\WMPLAY~1.exe", "C:\\PROGRAM\\WINDOW~1\\WMPLAY~1.exe","\"This is the first argument passed by spawn.exe!\"",NULL ); if(error == 0)printf("Program lauched successfully!\n"); else { printf("%d\n",error); system("PAUSE"); } } else { printf("%s\n\n",argv[1]); system("PAUSE"); } return 0; }
scanf() Function in C
Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
Syntax for scanf() Function in C
#include <stdio.h> int scanf ( const char * format, ... );
C string that contains a sequence of characters that control how characters extracted from the stream are treated: • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread. • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. A format specifier for scanf follows this prototype: %[*][width][length]specifier
Where the specifier character at the end is the most significant component, since it defines which characters are extracted, their interpretation and the type of its corresponding argument:
i – integer
Any number of digits, optionally preceded by a sign (+ or -). Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f). Signed argument.
d or u – decimal integer
Any number of decimal digits (0-9), optionally preceded by a sign (+ or -). d is for a signed argument, and u for an unsigned.
o – octal integer
Any number of octal digits (0-7), optionally preceded by a sign (+ or -). Unsigned argument.
x – hexadecimal integer
Any number of hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -). Unsigned argument.
f, e, g – floating point number
A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
c – character
The next character. If a width other than 1 is specified, the function reads exactly width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
s – string of characters
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
p – pointer address
A sequence of characters representing a pointer. The particular format used depends on the system and library implementation, but it is the same as the one used to format %p in fprintf.
[characters] – scanset
Any number of the characters specified between the brackets. A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters] – negated scanset
Any number of characters none of them specified as characters between the brackets.
n – count
No input is consumed. The number of characters read so far from stdin is stored in the pointed location.
A % followed by another % matches a single %. Except for n, at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.
The format specifier can also contain sub-specifiers: asterisk (*), width and length (in that order), which are optional and follow these specifications:
An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).
Specifies the maximum number of characters to be read in the current reading operation (optional).
One of hh, h, l, ll, j, z, t, L (optional). This alters the expected type of the storage pointed by the corresponding argument (see below).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type. There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function. These arguments are expected to be pointers: to store the result of a scanf operation on a regular variable, its name should be preceded by the reference operator (&) (see example). On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned. If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* read formatted data from stdin by scanf() function example */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ char name[10]; int age; int result; /* Ask the user to enter their first name and age */ printf("Please enter your first name and your age.\n"); /* Read a name and age from the user */ result = scanf("%s %d",name, &age); /* We were not able to parse the two required values */ if (result < 2) { /* Display an error and exit */ printf("Either name or age was not entered\n\n"); exit(0); } /* Display the values the user entered */ printf("Name: %s\n", name); printf("Age: %d\n", age); return 0; }
Standard Input/Output Devices in C
When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement. When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files. C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen. • Standard input: stdin(Keyboard). • Standard output: stdout(Screen). • Standard error: stderr(Your screen). The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/* C language provides standard library functions to read any given input and to display data on the console. */ #include<stdlib.h> #include<stdio.h> int main() { char chr; float num1; double num2; int i; printf("Enter a character: "); scanf("%c", &chr); // When %c is used, a character is displayed printf("You entered %c.\n",chr); // When %d is used, ASCII value is displayed printf("ASCII value is %d.", chr); printf("Enter a number: "); scanf("%f", &num1); printf("Enter another number: "); scanf("%lf", &num2); printf("num1 = %f\n", num1); printf("num2 = %lf", num2); printf("Enter a value: "); i = getchar(); printf("You entered: "); putchar(i); return 0; }
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value. In place of void we can also use int return type of main() function, at that time main() return integer type value.
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); return 0; }
pipe() Function in C
The pipe() function shall create a pipe and place two file descriptors, one each into the arguments fildes[0] and fildes[1], that refer to the open file descriptions for the read and write ends of the pipe. Their integer values shall be the two lowest available at the time of the pipe() call. The O_NONBLOCK and FD_CLOEXEC flags shall be clear on both file descriptors. (The fcntl() function can be used to set both these flags.) Data can be written to the file descriptor fildes[1] and read from the file descriptor fildes[0]. A read on the file descriptor fildes[0] shall access data written to the file descriptor fildes[1] on a first-in-first-out basis. It is unspecified whether fildes[0] is also open for writing and whether fildes[1] is also open for reading.
Syntax for pipe() Function in C
#include <unistd.h> int pipe(int fildes[2]);
The file descriptor A process has the pipe open for reading (correspondingly writing) if it has a file descriptor open that refers to the read end, fildes[0] (write end, fildes[1]). Upon successful completion, pipe() shall mark for update the st_atime, st_ctime, and st_mtime fields of the pipe. Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error. The pipe() function shall fail if:
More than {OPEN_MAX} minus two file descriptors are already in use by this process.
The number of simultaneously open files in the system would exceed a system-imposed limit. • Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the other process reads from the pipe. It opens a pipe, which is an area of main memory that is treated as a "virtual file". • The pipe can be used by the creating process, as well as all its child processes, for reading and writing. One process can write to this "virtual file" or pipe and another related process can read from it. • If a process tries to read before something is written to the pipe, the process is suspended until something is written. • The pipe system call finds the first two available positions in the process's open file table and allocates them for the read and write ends of the pipe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* create an interprocess channel by pipe() function code example */ // C program to illustrate pipe system call in C shared by Parent and Child #include <stdio.h> #include <unistd.h> #define MSGSIZE 16 char* msg1 = "hello, world #1"; char* msg2 = "hello, world #2"; char* msg3 = "hello, world #3"; int main() { char inbuf[MSGSIZE]; int p[2], pid, nbytes; if (pipe(p) < 0) exit(1); /* continued */ if ((pid = fork()) > 0) { write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE); // Adding this line will // not hang the program // close(p[1]); wait(NULL); } else { // Adding this line will // not hang the program // close(p[1]); while ((nbytes = read(p[0], inbuf, MSGSIZE)) > 0) printf("% s\n", inbuf); if (nbytes != 0) exit(2); printf("Finished reading\n"); } return 0; }
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) { // run code if test expression is true } else { // run code if test expression is false }
If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* if else statement in C language */ // Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
#include Directive in C
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include: • Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. • User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax for #include Directive in C
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */ // C program to illustrate file inclusion // <> used to import system header file #include <stdio.h> // " " used to import user-defined file #include "process.h" // main function int main() { // add function defined in process.h add(10, 20); // mult function defined in process.h multiply(10, 20); // printf defined in stdio.h printf("Process completed"); return 0; }
close() Function in C
Closes a file descriptor, fildes. This frees the file descriptor to be returned by future open() calls and other calls that create file descriptors. The fildes argument must represent a hierarchical file system (HFS) file. When the last open file descriptor for a file is closed, the file itself is closed. If the file's link count is 0 at that time, its space is freed and the file becomes inaccessible. When the last open file descriptor for a pipe or FIFO file is closed, any data remaining in the pipe or FIFO file is discarded. close() unlocks (removes) all outstanding record locks that a process has on the associated file.
Syntax for close() Function in C
#include <unistd.h> int close(int fildes);
The descriptor of the socket to be closed. Behavior for sockets: close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed. All sockets should be closed before the end of your process. You should issue a shutdown() call before you issue a close() call for a socket. For AF_INET and AF_INET6 stream sockets (SOCK_STREAM) using SO_LINGER socket option, the socket does not immediately end if data is still present when a close is issued. The following structure is used to set or unset this option, and it can be found in sys/socket.h.
struct linger { int l_onoff; /* zero=off, nonzero=on */ int l_linger; /* time is seconds to linger */ };
If the l_onoff switch is nonzero, the system attempts to deliver any unsent messages. If a linger time is specified, the system waits for n seconds before flushing the data and terminating the socket. For AF_UNIX, when closing sockets that were bound, you should also use unlink() to delete the file created at bind() time. Special behavior for XPG4.2: If a STREAMS-based fildes is closed and the calling process was previously registered to receive a SIGPOLL signal for events associated with that STREAM, the calling process will be unregistered for events associated with the STREAM. The last close() for a STREAM causes the STREAM associated with fildes to be dismantled. If O_NONBLOCK is not set and there have been no signals posted for the STREAM, and if there is data on the module's write queue, close() waits for an unspecified time (for each module and driver) for any output to drain before dismantling the STREAM. The time delay can be changed using an I_SETCLTIME ioctl() request. If the O_NONBLOCK flag is set, or if there are any pending signals, close() does not wait for output to drain, and dismantles the STREAM immediately. Note: z/OS® UNIX services do not supply any STREAMS devices or pseudodevices. See open() - Open a file for more information. If fildes refers to the master side of a pseudoterminal, a SIGHUP signal is sent to the process group, if any, for which the slave side of the pseudoterminal is the controlling terminal. If fildes refers to the slave side of a pseudoterminal, a zero-length message will be sent to the master. If fildes refers to a socket, close() causes the socket to be destroyed. If the socket is connection-oriented and the SO_LINGER option is set for the socket and the socket has untransmitted data, then close() will block for up to the current linger interval until all data is transmitted. If successful, close() returns 0. If unsuccessful, close() returns -1 and sets errno to one of the following values:
The call did not complete because the specified socket descriptor is currently being used by another thread in the same process. For example, in a multithreaded environment, close() fails and returns EAGAIN when the following sequence of events occurs (1) thread is blocked in a read() or select() call on a given file or socket descriptor and (2) another thread issues a simultaneous close() call for the same descriptor.
fildes is not a valid open file descriptor, or the socket parameter is not a valid socket descriptor.
The file cannot be closed because it is blocked.
close() was interrupted by a signal. The file may or may not be closed.
Added for XPG4.2: An I/O error occurred while reading from or writing to the file system.
fildes does not exist. The minor number for the file is incorrect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* close a file descriptor by close() function code example */ #include <fcntl.h> #include <unistd.h> #include <stdlib.h> int main( void ) { int filedes; filedes = open( "file", O_RDONLY ); if( filedes != -1 ) { /* process file */ close( filedes ); return EXIT_SUCCESS; } return EXIT_FAILURE; }

Demonstrate multiple loop control variables. This is a testing of converge. Copies one string into another. It copies characters to both the ends, converging at the middle...
Generates fibonacci series. In fibonacci series the first 2 numbers in the Fibonacci sequence are 0, 1, each Subsequent Number is the sum of the previous two. Example 0, 1, 1, 2, 3, 5, 8,
Prints 3 characters forward and backward to demonstrate character printing in C program code example. Define the first character, define the second character, define the third
How to find sum of all odd numbers in a given range in C programming. Input upper limit to find sum of odd numbers from user. Store it in a variable say N. Initialize other variable to
C Converts a decimal number into binary and count the number of 1s. The c program uses module operation and multiplication with base 2 operation for conversion. It also uses
C Language program code add two Complex numbers by passing structure to a function. In this program code, structures j1 and j2 are passed as an argument of function add(). The