How to check if stdout has been redirected to NUL on Windows (a.k.a. /dev/null on Linux)? - c

How can I check if my program's stdout has been redirected to NUL?
That way I can avoid outputting data since it's pointless.
I mainly need this for Windows, but if you have a Linux solution, it might be helpful for others in the future, so feel free to post that as well.

There are probably other ways to do this (and it wouldn't be a surprise if there turns out to be a proper function for it I've overlooked), but here's one way:
enum
{
Output_Console,
Output_File,
Output_NUL,
};
bool GetOutputHandleType(int* piType)
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
if (h)
{
BY_HANDLE_FILE_INFORMATION fi;
if (GetFileInformationByHandle(h, &fi))
{
*piType = Output_File;
return true;
}
if (GetLastError() == ERROR_INVALID_FUNCTION)
{
*piType = Output_NUL;
return true;
}
if (GetLastError() == ERROR_INVALID_HANDLE)
{
*piType = Output_Console;
return true;
}
}
return false;
}

I figured it out myself. It's annoying.
#include <Windows.h>
#include <io.h>
#pragma comment(lib, "ntdll.lib") // can instead use GetProcAddress (below)
extern "C" NTSTATUS __stdcall NtQueryVolumeInformationFile(
HANDLE FileHandle, struct _IO_STATUS_BLOCK *IoStatusBlock,
void *FsInformation, unsigned long Length,
enum _FSINFOCLASS FsInformationClass);
bool isdevnull(FILE *file)
{
struct FILE_FS_DEVICE_INFORMATION
{ unsigned long DeviceType, Characteristics; } fsinfo;
struct { void *info, *status; } iosb;
typedef NTSTATUS (__stdcall *PNTQIF)(
HANDLE FileHandle, struct _IO_STATUS_BLOCK *IoStatusBlock,
void *FsInformation, unsigned long Length,
enum _FSINFOCLASS FsInformationClass);
PNTQIF const ntqif =
true // True if you have ntdll.lib, false otherwise
? NtQueryVolumeInformationFile
: (PNTQIF) GetProcAddress(
GetModuleHandle(TEXT("ntdll.dll")),
"NtQueryVolumeInformationFile");
return ntqif(
(HANDLE) _get_osfhandle(_fileno(stdout)),
(struct _IO_STATUS_BLOCK *)&iosb,
&fsinfo, sizeof(fsinfo),
(enum _FSINFOCLASS)4
) == 0 && fsinfo.DeviceType == 0x00000015 /*FILE_DEVICE_NULL*/;
}
int main()
{
bool b = isdevnull(stdout);
}

Related

store or check value of getenv() only once in a shared library/DLL

I have a function to print debug logs which has to be toggled depending on the environment variable. Instead of checking the env var each time the print_trace() is called, what should be the best method to store it and reuse that value?
void print_trace(const char* msg)
{
const char* s = getenv("DEBUG_TRACE");
if(!strcmp(s,"ON"))
printf(msg);
}
There is no main() as this is a shared library.
You could save the result of the decision in a static variable.
void print_trace(const char* msg)
{
static int debug_on = -1; // -1 == not yet set
if (debug_on == -1) {
const char* s = getenv("DEBUG_TRACE");
debug_on = s && (strcmp(s, "ON") == 0);
}
if(debug_on)
printf("%s", msg);
}
You could use the thread safe call_once feature that was added in C11.
Example:
#include <threads.h>
static bool debug_mode; // your debug mode flag
void set_debug_mode(void) { // this is only called once
const char *s = getenv("DEBUG_TRACE");
debug_mode = s && !strcmp(s, "ON");
}
void print_trace(const char* msg) {
static once_flag flag = ONCE_FLAG_INIT;
call_once(&flag, set_debug_mode); // called once to set debug_mode
if(debug_mode)
printf(msg);
}

How to determine if a declared extern variable is defined or initialized in some C file

I have some table of structs that get compiled differently depending on what driver I am using.
I want to be able to check if a certain driver has been compiled (or by relation, if its table is defined).
I've look all over but I can't seem to find a way to determine if a declared extern variable has been defined or
if there's some way to check if a c source file has been compiled (and linked) within a given application. I had looked at using some macro magic like the container_of macro however I've so far come up short.
for example say I have the following:
checkFile.c
#include "neutral.h"
#include "fileA.h"
#include "fileB.h"
bool setTable(int type, someStruct_t *table) {
/*
This doesn't work
fails to compile with:
undefined reference to fileA_Table
ironically this is what I'm trying to check
*/
switch (type) {
case FILEA:
if (fileA_Table) {
someTable = &fileA_Table;
return true;
}
else {
someTable = NULL;
return false;
}
break;
case FILEB:
if (fileB_Table) {
someTable = &fileB_Table;
return true;
}
else {
someTable = NULL;
return false;
}
break;
default:
someTable = NULL;
return false;
}
}
neutral.h
typedef struct {
int memberA;
bool memberB;
} someStruct_t;
extern someStruct_t fileA_table[];
extern someStruct_t fileB_table[];
fileA.c
#include "neutral.h"
someStruct_t fileA_table[] = {
{
.memberA = 0;
.memberB = false;
},
{
.memberA = 5;
.memberB = false;
}
}
fileB.c
#include "neutral.h"
someStruct_t fileB_table[] = {
{
.memberA = 14;
.memberB = true;
},
{
.memberA = 5;
.memberB = true;
}
}
I'm not even sure that this is something that I can do in C and really the fundamental problem I'm trying to solve is initializing some type of interface that relies on fileA or fileB and ensuring which arrays are available to use from fileA and/or fileB. Note this
Ideally I'd actually like if I could just use file_table but I don't think that's possible if both fileA and fileB are compiled.
Note this should work regardless of if fileA or fileB or both files are compiled.
Any help is much appreciated.
Your code can safely assume that the variable exists.
If it doesn't, you'll get an error from the compiler during the linking stage when you attempt to link your object files into an executable.
If you want some kind of conditional compilation, you'll need to set a macro based on what's available and then check for that macro in various parts of your code.
For example:
#include "neutral.h"
#ifdef USE_FILE_A
#include "fileA.h"
#elif defined USE_FILE_B
#include "fileB.h"
#endif
bool setTable(someStruct_t **table)
{
#ifdef USE_FILE_A
*table= &fileA_Table;
return true;
#elif defined USE_FILE_B
*table= &fileB_Table;
return true;
#else
*table = NULL;
return false;
}
With the updated code:
#include "neutral.h"
#ifdef HAS_FILE_A
#include "fileA.h"
#endif
#ifdef HAS_FILE_B
#include "fileB.h"
#endif
bool setTable(int type, someStruct_t *table)
{
switch (type) {
case FILEA:
#ifdef HAS_FILE_A
someTable = &fileA_Table;
return true;
#else
someTable = NULL;
return false;
#endif
break;
case FILEB:
#ifdef HAS_FILE_B
someTable = &fileB_Table;
return true;
#else
someTable = NULL;
return false;
#endif
break;
default:
someTable = NULL;
return false;
}
}
Based on Bill Lynch's suggestion I looked into strong and weak symbols here and here and found an appealing solution. Roughly this is what I came up with.
checkFile.c
#include "neutral.h"
#include "fileA.h"
#include "fileB.h"
bool setTable(int type, someStruct_t *table) {
/*
* This will compile and if fileA_table has not been
* defined in fileA then it will evaluate to 0
*/
switch (type) {
case FILEA:
if (fileA_Table) {
someTable = &fileA_Table;
return true;
}
else {
someTable = NULL;
return false;
}
break;
case FILEB:
if (fileB_Table) {
someTable = &fileB_Table;
return true;
}
else {
someTable = NULL;
return false;
}
break;
default:
someTable = NULL;
return false;
}
}
neutral.h
typedef struct {
int memberA;
bool memberB;
} someStruct_t;
__attribute__((weak)) extern someStruct_t fileA_table[];
__attribute__((weak)) extern someStruct_t fileB_table[];
fileA.c
#include "neutral.h"
someStruct_t fileA_table[] = {
{
.memberA = 0;
.memberB = false;
},
{
.memberA = 5;
.memberB = false;
}
}
fileB.c
#include "neutral.h"
someStruct_t fileB_table[] = {
{
.memberA = 14;
.memberB = true;
},
{
.memberA = 5;
.memberB = true;
}
}
I like this since it meant I could get the results I want with minimal impact to my interface and no impact to compiler options/commands.
I would have liked to use the same symbol for fileA and fileB to make the generic interface layer and the neutral header cleaner to get something like this:
neutral.h
typedef struct {
int memberA;
bool memberB;
} someStruct_t;
__attribute__((weak)) extern someStruct_t file_table[];
checkFile.c
#include "neutral.h"
#include "fileA.h"
#include "fileB.h"
bool setTable(int type, someStruct_t *table) {
if (file_Table) {
someTable = &file_table;
return true;
}
someTable = NULL;
return false;
}
This could be done so long as we compile the interface starting at checkFile.c as two seperate binaries. Once linking with fileA.c and once with fileB.c. This does add some complexity in build options, increases code size, and I'm not sure of the impact to performance however it makes the code more maintainable and much more so should there be several potential files and several types of tables that need to be checked.

FTW does not give "newest" directory

I have the following C code:
#include <ftw.h>
#define MAXPATHLEN 100
static time_t createtime = 0;
static char ftwpath[MAXPATHLEN];
[...]
ftw(somepath, get_writedir, 10);
if (ftwpath[0] == '\0') {
//Code assuming that the directory does not exist.
} else {
//Some code handeling
}
That is the method that ftw calls:
int get_writedir(const char *path, const struct stat *sb, int typeflag)
{
if (typeflag == FTW_D && sb->st_ctime > createtime) {
createtime = sb->st_ctime;
strlcpy(ftwpath, path, MAXPATHLEN);
}
return 0;
}
Generally speking this code works to some extend when typeflag is set to FTW_F, not FTW_D. When I do the latter, nothing happens.
When I do the prior: I do not always get the "newest created directory". What am I doing wrong here?

CreateThread wrapper function

I am currently working on a project where we have a C thread implementation for UNIX systems using pthreads. Now we want to be able to run this entire project on Windows as well, and I am translating all the threading for WIN32. Now I encountered a problem for which I could not come up with a decent solution.
I have the thrd_create() function:
static inline int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) {
Args* args = malloc(sizeof(Args));
args->arg = arg;
args->function = func;
*thr = CreateThread(NULL, 0, wrapper_function, (LPVOID) args, 0, NULL);
if (!*thr) {
free (args);
return thrd_error;
}
return thrd_success;
}
This function is supposed to create a new thread, and the user provides a start function. For convenience, I would like to leave the implementation that calls thrd_create() untouched if possible. For this reason, I created a wrapper_function:
static inline DWORD wrapper_function(LPVOID arg) {
Args * args;
args = (Args*) arg;
DWORD res = args->function(args->arg); //This does obviously not work
return res;
}
My question is: What DWORD should my wrapper function return? The function provided by the user for the pthread implementation has void return type, so I won't get any result from that. Any suggestions?
EDIT
Args looks like this:
struct Args {
void (*function)(void * aArg);
void* arg;
};
typedef struct Args Args;
According to manuals it is better to stick to a correct signature and use return value:
Windows
Pthreads
The other matter of concern would be the lifetime of args, I'd say the best way is for a caller to clean up, so they need to be tracked with your thread until it terminates.
An approximate API could be something along the lines of the following:
/* Your general error codes enumeration
* which should probably reside in a general
* header
*/
typedef enum {
OK = 0,
// Your application specific error codes
} error_t;
#ifdef _WIN32
#include <Windows.h>
typedef HANDLE thread_handle_t;
#else // assume pthreads
#include <pthread.h>
typedef pthread_t thread_handle_t;
#endif
typedef error_t(*entry_func_t)(void*);
typedef struct {
entry_func_t func;
void *args;
error_t _result;
thread_handle_t _handle;
} thread_t;
// returns OK(0) on success
// returns error code indicating a problem
error_t thread_create(thread_t *t);
An aproximate implementation would be:
#ifdef _WIN32
DWORD _win_entry_f(void *args) {
thread_t *t = args;
t->_result = t->func(t->args);
return 0; // Or some other Windows-specific value
}
error_t thread_create(thread_t *t) {
error_t err = OK;
if(!(t->_handle = ThreadCreate(NULL, 0, _win_entry_f, t, 0, NULL))) {
switch (GetLastError()) {
// Populate error with code
}
}
return err;
}
#else
void * _pthread_entry_f(void *args) {
thread_t *t = args;
t->_result = t->func(t->args);
return NULL; // Or some other pthreads specific value
}
error_t thread_create(thread_t *t, entry_func_t func, void *args) {
error_t err = OK;
switch(pthread_create(&t->_handle, NULL, _pthread_entry_f, t)) {
case 0: break;
// other cases populate err
}
return err;
}
#endif
Invokation would look somewhat like this.
error_t func(void* args) {
return OK;
}
.....................
thread_t t = { .func = func, .args = NULL };
thread_create(&t);
Obviously you'll need to implement your own cancelation, result collection, join, ...

Function pointers in FSM

HI.. I want an example of how to implement FSM using function pointers in C.
See this simple example on how to implement a finite state machine in C.
An example is too big to write as an answer here.
Here's an existing example, which I found by Googling for state machine c "function pointer": Implementing Efficient State Machines
Here is a little demo of using function pointers in ARDUINO. This example does not allow for concurrency. It perfectly transferable to normal C if make write the setup and loop inside main()
Each state is a void() function. Each state function is responsible for reading input and setting output. When this is done the function should return immediately. It will be called again directly. The function is also responsible for state-transition by calling the leave function immediately before returning. Each state function should have a static long variable for timekeeping.
A global variable state is set to point to the initial state in the setup routine.
I wanted timekeeping in the different states so i implemented the state transitions by 2 functions:
void enter(long *stateTime), this should be called the very first thing when entering the state functions. It activates the state if inactive end keeps time.
void leave(void (*next)(), long *statetime), this changes the global state pointer and deactivates the current state.
void (*state)();//function pointer for state machine
long prevMillis = 0;//timekeeper
const int LEDPIN = 13;
int counter1 = 0;
void enter(long *statetime){
if(*statetime==-1){//check for passive state
prevMillis = millis();//set timemark when entering state
}//if(statetime==0)
*statetime = millis()-prevMillis;//keep time
}//enter()
void leave(void (*next)(), long *statetime){
*statetime=-1;//set state to passive
state=next;//point to next state
}//leave()
void off500ms(){
static long stateMillis;//timer for this state
enter(&stateMillis);//update timer
digitalWrite(LEDPIN, LOW);
if(stateMillis>499){//check if time is up
leave(on500ms, &stateMillis);
}//if(stateMillis>499)
}//off500ms()
void off2s(){
static long stateMillis;//timer for this state
enter(&stateMillis);//update timer
digitalWrite(LEDPIN, LOW);
if(stateMillis>1999){//check if time is up
leave(on500ms, &stateMillis);
}//if(stateMillis>499)
}//off2s()
void on500ms(){
static long stateMillis;//timer for this state
enter(&stateMillis);//update timer
digitalWrite(LEDPIN, HIGH);
if(stateMillis >499){//time is up
if(++counter1==6){//number of blinks
leave(off2s, &stateMillis);
counter1=0;//reset counter
}else{//if(++counter1==6)
leave(off500ms, &stateMillis);
}//if(++counter1==6)
}//if(stateMills>499)
}//on500ms
void setup(){
pinMode(LEDPIN, OUTPUT);
state = on500ms;//set initial state
}/setup()
void loop(){
state();//start FSM
}//loop
I would say initialize a array of pointers to event handlers. So each element of a array is a function pointer to a particular event which is part of an enum.
if foo is your array of function pointers which is initialized to event then call foo[event]() when any event occurs.
Try coding for calling a function pointer first, next you can move to array and come back to SO if there are more doubts.
For a start you can read about function pointers here.
State transtion code can be utilize either by array or switch case. Written under if else directive.
#include <stdio.h>
#include <stdlib.h>
int entry_state(void);
int foo_state(void);
int bar_state(void);
int exit_state(void);
enum state_codes lookup_transitions(enum state_codes, enum ret_codes);
/* array and enum below must be in sync! */
int (* state[])(void) = { entry_state, foo_state, bar_state, exit_state};
enum state_codes { entry, foo, bar, end};
enum ret_codes { ok, fail, repeat};
struct transition {
enum state_codes src_state;
enum ret_codes ret_code;
enum state_codes dst_state;
};
/* transitions from end state aren't needed */
struct transition state_transitions[] = {
{entry, ok, foo},
{entry, fail, end},
{foo, ok, bar},
{foo, fail, end},
{foo, repeat, foo},
{bar, ok, end},
{bar, fail, end},
{bar, repeat, foo}};
int main(int argc, char *argv[]) {
enum state_codes cur_state = entry;
enum ret_codes rc;
int (* state_fun)(void);
for (;;) {
state_fun = state[cur_state];
rc = state_fun();
if (end == cur_state)
break;
cur_state = lookup_transitions(cur_state, rc);
}
return EXIT_SUCCESS;
}
/*
* lookup_transition() function has time complexity of class O(n).
* We can optimize it.
* */
enum state_codes
lookup_transitions(enum state_codes cur_state, enum ret_codes rc)
{
#if 0
switch (cur_state) {
case entry:
cur_state = ((rc == ok) ? (foo) : (end));
break;
case foo:
cur_state = ((rc == ok) ? (bar) : ((rc == fail) ? (end) : (foo)));
break;
default:
cur_state = ((rc == ok) ? (end) : ((rc == fail) ? (end) : (foo)));
break;
}
return cur_state;
#else
char arr_size = (sizeof(state_transitions) / sizeof(state_transitions[0])); /* This can be shifted to main function to avoid redundant job. */
char count;
for (count = 0; count < arr_size; count++) {
if ((state_transitions[count].src_state == cur_state) && (state_transitions[count].ret_code == rc)) {
return (state_transitions[count].dst_state);
}
}
#endif
}
int entry_state(void)
{
int st;
enum ret_codes rc;
printf("YOU ARE IN ENTRY STATE.\nEnter 0/1: ");
scanf("%d", &st);
rc = ((st == 1) ? (fail) : (ok));
return rc;
}
int foo_state(void)
{
int st;
enum ret_codes rc;
printf("YOU ARE IN FOO STATE.\nEnter 0/1/2: ");
scanf("%d", &st);
rc = ((st == 0) ? (ok) : ((st == 2) ? (repeat) : (fail)));
return rc;
}
int bar_state(void)
{
int st;
enum ret_codes rc;
printf("YOU ARE IN BAR STATE.\nEnter 0/1/2: ");
scanf("%d", &st);
rc = ((st == 0) ? (ok) : ((st == 2) ? (repeat) : (fail)));
return rc;
}
int exit_state(void)
{
printf("YOU ARE IN EXIT STATE.\n");
exit(EXIT_SUCCESS);
}

Resources