Tag Archive: C/C++

Obtain a list of process scheduling policy and priority

Normally, you can read the file /proc/[pid]/sched and get the related information. But since I am using a simplified one, the sched file is not presented. And I need to figure out another way to get it. I finally found there is a C library, <sched.h>, to do that. You can find the following declarations in the library.

struct sched_param {
    int sched_priority;
};

/* Set scheduling parameters for a process */
int sched_setparam(pid_t pid, const struct sched_param *param);

/* Retrieve scheduling parameters for a particular process */
int sched_getparam(pid_t pid, struct sched_param *param);

/* Set scheduling algorithm and/or parameters for a process */
int sched_setscheduler(pid_t pid, int policy, const struct sched_param *param);

/* Retrieve scheduling algorithm for a particular purpose */
int sched_getscheduler(pid_t pid);

In this case, we only need sched_getparam() to obtain scheduling priority and sched_getscheduler() to obtain scheduling policy.
(more…)

Avoid writing 0x0A as 0x0D0A: Be careful of File Access Mode

When dealing with file I/O in C/C++, we should first open a file with fopen:
FILE * fopen ( const char * filename, const char * mode )
The parameter mode refers to “File Access Mode“. You have the following options (from cplusplus.com):

“r” read: Open file for input operations. The file must exist.
“w” write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
“a” append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
“r+” read/update: Open a file for update (both for input and output). The file must exist.
“w+” write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
“a+” append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

(more…)