I'm tasked with creating a popen() function using Pipes, which I have already completed. The catch is that the function must ALSO be named popen, not mypopen or popen2 etc.
I'm looking for someone to guide me in the right direction as to how I can accomplish this.
Currently I have a header file popen.h and another filed popen.c that I have created.
popen.h just has
void popen(char *arr[]);
While popen.c has the actual popen function code (Which works, just not when the function name is popen).
Currently I'm getting a previous declaration error upon compilation when my function is called popen.
How can I let the compiler choose between the two different popen functions, mine and stdio.h version.
Just #define popen my_popen before declaring, defining and using your function, but after including <stdio.h>.
popen.h
#define popen my_popen
void popen(char *arr[]);
popen.c
#include <stdio.h>
#include "popen.h"
void popen(char *arr[]){ printf("that's NOT the stdio's popen\n"); }
main.c
#include <stdio.h>
#include "popen.h"
int main(void){
popen(0); printf("done\n");
}
Similarly, you can hide the stdio's popen by defining popen to stdio_popen before including <stdio.h> and undefining it afterwards, if you really want to have a symbol named popen:
#define popen stdio_popen
#include <stdio.h>
#undef popen
void popen(char *arr[]){ printf("that's NOT the stdio's popen\n"); }
int main(void){
popen(0); printf("done\n");
}
$ nm a.out | grep popen
0000000000001160 T popen
Such nasty tricks are only useful when having to combine ornery source codes which pollute each other's namespace. There's zero reason to name a function you just wrote popen() and not something else, unless it's a drop-in replacement, with the same interface as the standard one.
If you want to have popen safely you must also make sure that you aren’t using <stdio.h>as this is where the normal popen is located, and your linker will not like it if there are two identical symbols named popen.
Related
Let's look at the gettid system call as an example:
http://man7.org/linux/man-pages/man2/gettid.2.html
I know gettid is not implemented in libc and I need to make a system call directly in order to use it (syscall(SYS_gettid)). I have verified this myself with this C code:
#include <stdio.h>
#include <sys/types.h>
int main(){
pid_t a = gettid();
return 0;
}
which doesn't link and gives this warning when compiling: warning: implicit declaration of function 'gettid'; did you mean 'getline'.
Now my question is, why has the Linux documentation documented it as if this function actually exists?
SYNOPSIS
#include <sys/types.h>
pid_t gettid(void);
They have no example of how to make a direct system call and instead they have the above code snippet which doesn't exist and can't be used. Is there something I'm missing?
The syscall doesn't have a wrapper in the GNU C library (before 2.30), this is just a prototype of how the function would look if it did.
As noted in the man page:
NOTES
Glibc does not provide a wrapper for this system call; call it using syscall(2).
Here's an example of the gettid wrapper:
#define _GNU_SOURCE
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
pid_t gettid(void)
{
pid_t tid = (pid_t)syscall(SYS_gettid);
return tid;
}
As you can see, this is the same prototype as described in the man-page. The prototype in the man-page is just for reference, so you can create a wrapper around the system call if you (or the libc developers) so choose.
If you're just starting to learn C, I suggest you stop trying to understand system calls and their wrappers in the C library until you have more experience in the language. The difference will then be clear.
I have a version of a program that used to compile to a *.o file, but now it does not, and gives a compiler error.
I have tried to compile my code with gcc compiler on Linux, and the compile fails.
#include <stdio.h>
int isatty();
long isatty_(lio_number)
long *lio_number;
{
int file_desc;
if ((*lio_number)==5)
{
file_desc = stdin->_file;
return isatty(file_desc);
}
else
return 0;
}
I expect the command gcc -c isatty.c to yield isatty.o but it does not. Instead, I get this message:
isatty.c: In function ‘isatty_’:
isatty.c:11: error: ‘struct _IO_FILE’ has no member named ‘_file’
Never use any members of the FILE structure.
Use fileno(stdin) instead of stdin->_file.
The member _file is a MinGW-specific name for the file descriptor, while fileno is a widely-supported POSIX-compliant function.
Along with that, you may want to #include <unistd.h> instead of defining isatty explicitly.
If you're limited to writing your code this way for some reason, don't expect it to be portable. Otherwise, this should work:
#include <stdio.h>
#include <unistd.h>
long isatty_(long *lio_number)
{
int file_desc;
if (*lio_number == 5)
{
file_desc = fileno(stdin);
return isatty(file_desc);
}
else
{
return 0;
}
}
What this changes is that it includes unistd.h which provides a declaration for isatty, it includes the types of the arguments within the function definition, and it uses fileno(stdin) instead of stdin->_file, of which the former is much more portable. It also improves the formatting so others can read your code if they need to.
Modernize the code. The original seems to be targeting some ancient Unix. This should work on more recent POSIX-compliant systems, since virtually every such system should provide the fileno() function. Changing the code to standard C is also a good idea.
So use fileno(), include <unistd.h> instead of forward declaring isatty(), and use standard C function parameter declarations:
#include <stdio.h>
#include <unistd.h>
long isatty_(long *lio_number)
{
if (*lio_number == 5)
{
return isatty(fileno(stdin));
}
return 0;
}
I'm wondering whether a C file can be both included in another script (through a header file), and also run independently (by having its own main function). That is, the C file can be included to provide its functions to another C script, but can also itself be directly ran to provide some alternate functionality.
For example, a python script can do this;
def functionsToBeImported():
# code to be run by an importing script
pass
if __name__ == '__main__':
# code to be run by this script independently
pass
This code can be imported (import ABOVESCRIPT) by another python file to give access to functionsToBeImported, or independently run (python ABOVESCRIPT.py) to execute the code within the if block.
I've attempted to do this in C via myScript.c:
#include "myScript.h"
void functionsToBeImported() {
}
int main (int narg, char* varg[]) {
}
myScript.h:
#ifndef MY_SCRIPT_H_
#define MY_SCRIPT_H_
void functionsToBeImported();
#endif // MY_SCRIPT_H_
but trying to include this in anotherScript.c:
#include "myScript.h"
int main (int narg, char* varg[]) {
functionsToBeImported();
}
and trying to compile via
gcc -std=c99 -c myScript.c
gcc -std=c99 -c anotherScript.c
gcc -std=c99 -o anotherScript anotherScript.o myScript.o -lm
gives be a compilation error
duplicate symbol _main in:
myScript.o
anotherScript.o
How can I achieve this 'double-use' script?
You cannot link both anotherScript.o and myScript.o, but you could do something like this:
#define main ignored_main
// Include myScript.c, not myScript.h
#include "myScript.c"
#undef main
int main (int narg, char* varg[]) {
functionsToBeImported();
}
I have actually seen things like this in code very widely used in production, although I cannot recommend this style (but it is sometimes a tempting shortcut).
Another option is to include the main function only if a preprocessor macro is defined, like this (in myScript.c):
#include "myScript.h"
void functionsToBeImported() {
}
#ifdef USE_MAIN
int main (int narg, char* varg[]) {
}
#endif // USE_MAIN
This is similar in spirit to the Python approach. But again, you will have to compile this file twice into separate object files.
Note: C files are not scripts.
You cannot have two main functions, as C is a procedural language, meaning you must do one thing at a time (unless you are multithreading, in which case you would still only have one main function).
HOWEVER, there is something quite close to replicating what you want. What you can do is first, write the main method only in the first included file. In the main file, set the atexit() function from the C stdlib.h file (which calls another function at the end of main) to a main2() function (make sure that there is a prototype of each main#() function in the first header as well, and implement all of the functions eventually). Define a macro called MAIN_ONE in the function with the original main. In each consecutively included file, implement the next main and create a macro so that checks to see if the function was implemented can be made. However, the natural, and most efficient way to make a program in C is to just have one main function.
Example:
//In first included file
#include //Some IDEs automaticaly include this. This must be included since it is where the atexit() function resides
#define MAIN_ONE
void main2(); //For the moment, this is only a prototype.
void main3();
//etc. Until you have created the maximum number of main functions that you can have
int main() {
//do something
atexit(main2); // This will execute the function main1() once main returns
//All "fake" mains must be void, because atexit() can only receive void functions
}
//In second included file
#if defined(MAIN_THREE) //start from the maximum number of main functions possible
#define MAIN_THREE //The define is for preprocessor-checking purposes
void main4() {
atexit(main5);
}
#elif defined(MAIN_TWO) //start from the maximum number of main functions possible
#define MAIN_TWO
void main3() {
atexit(main5);
}
//Keep repeating until you reach #ifdef(MAIN_ONE)
#endif
//At the bottom of the main C file
//This is done in order to make sure that all functions have actually been created and reside in memory so that an error does not occur
//(all unused functions are initialized with an empty function here)
#if defined(MAIN_THREE) //start from the maximum number of main functions possible
//Do nothing because if MAIN_THREE is defined when main4(), the last main in my example has already been implemented.
//Therefore, no more functions need to be created
#elif defined(MAIN_TWO) //start from the maximum number of main functions possible
#define MAIN_TWO //Since more mains after main2 can be present, another macro for future checks needs to be defined
void main3() {
}
//Keep repeating until you reach #ifdef(MAIN_ONE)
#endif
I am learning C.
In this program
I use sleep function to slowdown a count down.
My text book doesn't specify a library I should include to use the sleep function.
So I use it without including any special library for it and it works.
But it gives me this warning message in codeblocks.
I tried to include <windows.h> but still the same warning message appears.
warning D:\Project\C language\trial8\trial8.c|19|warning: implicit
declaration of function `sleep'|
And here is my code.
#include <stdio.h>
int main()
{
int start;
do
{
printf("Please enter the number to start\n");
printf("the countdown (1 to 100):");
scanf("%d",&start);
}
while(start<1 || start>100);
do
{
printf("T-minus %d\n",start);
start--;
sleep(3000);
}
while(start>0);
printf("Zero!\n Go!\n");
return(0);
}
I want to know what does the warning message mean? How important is it? Is there anything that I should do about it? Note that the program works anyway.
The issue is in the libraries (header files):
on Windows:
#include <windows.h> and Sleep(1000); => 1000 milliseconds
on Linux:
#include <unistd.h> and sleep(1); => 1 second
The function sleep is not part of C programming language. So, C compiler needs a declaration/prototype of it so that it can get to know about about number of arguments and their data types and return data type of the function. When it doesn't find it, it creates an Implicit Declaration of that function.
In Linux, sleep has a prototype in <unistd.h> and in windows, there is another function Sleep which has a prototype in <windows.h> or <synchapi.h>.
You can always get away with including header, if you explicitly supply the prototype of the function before using it. It is useful when you need only few functions from a header file.
The prototype of Sleep function in C on windows is:
VOID WINAPI Sleep(_In_ DWORD dwMilliseconds);
Remember, it is always a good practice to supply the prototype of the function being used either by including the appropriate header file or by explicitly writing it. Even, if you don't supply it, compiler will just throw a warning most of the time and it will make an assumption which in most cases will be something that you don't want. It is better to include the header file as API might change in future versions of the Library.
Windows doesn't have the sleep function. Instead, it has Sleep, which takes the number of milliseconds to sleep:
VOID WINAPI Sleep(
_In_ DWORD dwMilliseconds
);
You'll need to either #include <windows.h> or #include <synchapi.h>, depending on the version of Windows you're running. See MSDN for more details.
Update in 2022:
As it is stated on the Linux man page here we need to include unistd.h and should do fine for all OS.
#include <stdio.h>
#include <unistd.h>
int main()
{
sleep(1); /* sleep for 1 second*/
printf("END\n");
return 0;
}
To make it more cross-platform, try this:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
I am looking for a way to find the name of the executable file which runs it. meaning that if I have a file called program which runs something I would like to get its name.
Using __FILE__ does not suite me since I need the executable name not the C files name which contains the code.
I am wondering if there is a gcc macro which can help me or a built in function which I couldn't find.
EDIT:
Also using argv[0] is not appropriate since I need to call the function not only inside main.
And passing the argv[0] parameter to all the functions that might need this parameter also isnt acceptable since it will be used in the entire system (I need to hash by it).
int main(int argc,char* argv[])
{
printf("%s",argv[0]);
return 0;
}
The first argument(argv[0]) contains the name of the program which is being run.
The standard definition for main() in C is:
int main(int argc, char **argv)
argv[0] contains the name of the program as executed.
From main, pass argv[0] to wherever you might need the program's name.
Or if a lot of functions need it and you want to avoid passing it around too much, assign it to a global variable.
You asked for macros as a solution, but they are expanded at compile time. And since the name of the executable file can be changed after compilation, what you want cannot be determined at compile time, so macros are out of question.
Often remembering argv[0] from main will be quite sufficient.
If this is not the case -- for example if you're a shared library, or if you worry that your caller started you with a faked argv[0] (this is possible but unusual), you can, on POSIX-compliant systems with a mounted /proc, use readlink to resolve /proc/self/exe and get a path to the main binary of the running process:
#include <limits.h>
#include <unistd.h>
// Note that readlink does not null-terminate the result itself. This
// is important if the link target contains null bytes itself, I suppose,
// but it means that you have to take care that the null-terminator is
// placed yourself if you're going to use the file name as a string.
char buf[PATH_MAX] = { 0 };
readlink("/proc/self/exe", buf, PATH_MAX);
And on Windows, there is the GetModuleFileName function:
#include <windows.h>
TCHAR buf[MAX_PATH];
GetModuleFileName(NULL, buf, MAX_PATH);
The startup name is given via main()'s argv[0] and can be considered constant.
So why not make it available through out the program using a global reference to it.
progname.h
#ifndef PROGNAME_H
#define PROGNAME_H
extern char * progname;
#endif
main.c
#include "progname.h"
char * progname = NULL;
int main(int argc, char ** argv)
{
progname = argv[0];
...
}
Access it from any where like so
module1.c
#include <stdio.h>
#include "progname.h"
void f(void)
{
printf("progname='%s'\n", progname ?progname :"<not set>");
}