cross-platform code for singleton process? - c++

I've got a situation to develop a code that can have only one instance per machine any time. And my code should be platform independent. Till this it is fine, but the problem is that I cannot have any other files except my binary. I've developed a code using fcntl, my logic is that I'll lock my binary itself, so every time the code runs it checks if it could lock and returns if it can't. This logic worked fine in ubuntu, solaris machines, but in windows I found that this logic no longer works as I can't open the running exe file. Here I attached my code where I got stuck. Please excuse me if you feel it's not the correct portal to ask, or if you feel my research is of no use. Any suggestion will be of great help to me.
#include<iostream>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
#define PATH "<my binary path>"
using namespace std;
int main(){
int lockfd;
FILE *FP = fopen(PATH,"wb");
if (!FP)
{
if(errno==16){
cout<<"programme is currently running hence I quit\n";// windows
}else{
cout<<"error while opening the given file\n";
cout<<"errno = "<<errno<<"\n";
}
return 1;
}else{
lockfd = fileno(FP);
}
cout<<lockfd<<"\n";
cout<<"errno = "<<errno<<"\n";
struct flock lock;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = F_WRLCK;//F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_pid = getpid();
int rc = fcntl(lockfd, F_SETLK, &lock);
cout<<"rc = "<<rc<<"\n";
cout<<"errno = "<<errno<<" eagain ="<<EAGAIN<<"\n";
if (rc == -1 && errno == EAGAIN) {
cout<<"cant lock now hence I quit\n";
return 0;
}else{
cout<<"lock done\n";
sleep(10);
//rest of the code//
}
}

The simpliest edit to make would be
#ifndef WIN32
#define PATH "/export/home/dath/Desktop/singleTon.bin"
#else
#define PATH "<some path in C that you want>"
#endif
Which forces the path to be one thing for windows, and something else for all other platforms.
That said there are other cleaner ways of doing this such as shared memory which would mean that you wouldn't have to worry about leaving files around the place or hard-coding their path.

Related

fopen / ofstream::open fail when creating a BMP file

Years ago I created a C++ function using FILE to create bitmap files. Recently (not sure when or why) this code is now failing when opening the file. The problem is with the open call ...
file_ptr = fopen("ScreenShots/Screenshot1.bmp", "wb");
Currently this results in an error 13, permission denied error. Change the filename extension to something else and the fopen works fine. For example,
file_ptr = fopen("ScreenShots/Screenshot1.bm2", "wb");
The file saves correctly and when changing the extension back to BMP I can display the file correctly in Paintshop.
Did a quick check using ofstream and same problem.
Any ideas why I get a permission denied error when trying to open BMP files to write data? For information I am using Visual Studio Community 2017 on Windows 10.
To give the complete section of code ...
BITMAPFILEHEADER bitmap_header;
BITMAPINFOHEADER bitmap_info;
FILE *file_ptr;
unsigned int count;
unsigned char tempRGB;
char filename[256];
bool finished;
// CREATE A UNIQUE FILENAME
count = 1;
finished = false;
do
{
// CREATE NAME
sprintf(filename, "ScreenShots/Screenshot%d.bmp", count);
// CHECK IF FILE EXISTS
errno = 0;
file_ptr = fopen(filename, "rb");
if (file_ptr)
{
// FILE EXISTS
fclose(file_ptr);
count = count + 1;
}
else
{
// UNIQUE FILENAME
file_ptr = fopen(filename, "wb");
if (file_ptr == NULL)
{
// UNABLE TO OPEN FOR WRITING - GIVE UP
// (USING OWN LOGGING CLASS)
jalog.log("\nERROR on Screenshot >");
jalog.log(filename);
jalog.log("< >");
jalog.log((short)errno);
return;
}
finished = true;
}
}
while (finished == false);
I've managed to find the issue ... Avast antivirus. I noticed that trying to do an open action for a BMP file took a few seconds while opening any other file type (successfully or unsuccessfully) was instantaneous. As something similar happens when running new programs I tried disabling all the Avast shields and I could successfully create a BMP file using the existing code.
For my own personal use I can whitelist my own programs, but annoying if I get to distributing the program to other people.
Thanks for the help ... and sorry for raising a C++ issue that in the end had nothing to do with C++!

Getting compilation error for "tlhelp32.h" in MinGW g++ compiler

I am writing a simple C++ app that checks whether a given exe file example:'a.exe' is running or not(windows OS), I have googled and found some code in the below link.
http://stackoverflow.com/questions/3355379/how-do-i-find-out-if-a-exe-is-running-in-c
The code mentioned above uses a header file "tlhelp32.h". I just copied the code and did some necessary changes then complied it in MinGW , there comes the next problem, all of the datatypes mentioned in that header files are errored out
ex: 'DWORD' does not name a type, 'LONG' does not name a type, 'WCHAR' does not name a type,'CHAR' does not name a type
I never faced this kind of issues before where an existed header file is failed to compile (yes it exist I've checked it).
really appreciate any help on this.
code below:
#include <tlhelp32.h>
int main()
{
PROCESSENTRY32 pe32 = {0};
HANDLE hSnap;
int iDone;
int iTime = 60;
bool bProcessFound;
while(true) // go forever
{
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
pe32.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnap,&pe32); // Can throw away, never an actual app
bProcessFound = false; //init values
iDone = 1;
while(iDone) // go until out of Processes
{
iDone = Process32Next(hSnap,&pe32);
if (strcmp(pe32.szExeFile,"a.exe") == 0) // Did we find our process?
{
bProcessFound = true;
iDone = 0;
}
}
if(!bProcessFound) // if we didn't find it running...
{
startProcess("C:\\MinGW\\"+"a.exe",""); // start it
}
Sleep(iTime*10); // delay x amount of seconds.
}
return 0;
}
As Richard Critten said adding "Windows.h" before "tlhelp32" resolves the issue and more over a function startprocess() in the above code has never existed so use shellexecute() to make it work
ex: ShellExecute(NULL, "open", "c:\MinGW\a.exe", NULL, NULL, SW_SHOWDEFAULT);

windows8 - _dup,_dup2

I use win8 Consumer preview build 8250 for executing a program, which works OK on win7
The program uses the following macros/functions:
#if defined(_WIN32)
#include <io.h>
#define streamDup(fd1) _dup(fd1)
#define streamDup2(fd1,fd2) _dup2(fd1,fd2)
#endif
static int acquireOutputStream()
{ int fd = streamDup(fileno(stdout));
FILE* f = freopen("tmp","w",stdout);
return fd; }
static void releaseOutputStream(int fd)
{ fflush(stdout);
streamDup2(fd,fileno(stdout));
close(fd);
}
The program performs the following:
for (int i = 0; i < 1000;++i) {
int fd = acquireOutputStream();
printf("redirect %d\n",i);
releaseOutputStream(fd);
printf("test %d\n",i);
}
Every time I run it ,it prints to file tmp random number of correct "redirect j" printings :
After it ,the file is empty for the remaining executions.(f pointer is never NULL in the acquireOutputStream)"test j" is always printed correctly.
What could be a problem? Is it a known issue on win 8?
There is one small issue i see with your code.
static void releaseOutputStream(int fd)
{ fflush(stdout);
streamDup2(fd,fileno(stdout));
close(fd);
}
In this function you do not close stdout prior to the dup2 call (fclose(stdout)).
Please add more detail to the question on exactly what you are seeing when running this code. It would help in diagnosing the issue.

linux - get pid of process

How can I get the PID of a service called abc using C++ on Linux without using a system call? I would appreciate any examples that you care to offer.
Since use of sysctl has been discouraged for ages now, the recommended way of doing this is by examining each of the process entries in /proc and reading the comm file in each folder. If, for your example, the contents of that file are abc\n, that's the process you're looking for.
I don't really speak C++, but here's a possible solution in POSIX C89:
#include <glob.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
pid_t find_pid(const char *process_name)
{
pid_t pid = -1;
glob_t pglob;
char *procname, *readbuf;
int buflen = strlen(process_name) + 2;
unsigned i;
/* Get a list of all comm files. man 5 proc */
if (glob("/proc/*/comm", 0, NULL, &pglob) != 0)
return pid;
/* The comm files include trailing newlines, so... */
procname = malloc(buflen);
strcpy(procname, process_name);
procname[buflen - 2] = '\n';
procname[buflen - 1] = 0;
/* readbuff will hold the contents of the comm files. */
readbuf = malloc(buflen);
for (i = 0; i < pglob.gl_pathc; ++i) {
FILE *comm;
char *ret;
/* Read the contents of the file. */
if ((comm = fopen(pglob.gl_pathv[i], "r")) == NULL)
continue;
ret = fgets(readbuf, buflen, comm);
fclose(comm);
if (ret == NULL)
continue;
/*
If comm matches our process name, extract the process ID from the
path, convert it to a pid_t, and return it.
*/
if (strcmp(readbuf, procname) == 0) {
pid = (pid_t)atoi(pglob.gl_pathv[i] + strlen("/proc/"));
break;
}
}
/* Clean up. */
free(procname);
free(readbuf);
globfree(&pglob);
return pid;
}
Caveat: if there are multiple running processes with the name you're looking for, this code will only return one. If you're going to change that, be aware that with the naive glob written, you'll also examine /proc/self/comm, which could potentially lead to a duplicate entry.
If there are multiple processes with the same name, there isn't really a way to ensure you got the right one. Many daemons have the ability to save their pids to a file for this reason; check your documentation.
Google has this covered :)
http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html
Although it does use sysctl, which is a system call!
It's C but should work just as well in C++

How do I find out if a .exe is running in c++?

How can you find out if an executable is running on Windows given the process name, e.g. program.exe?
The C++ standard library has no such support. You need an operating system API to do this. If this is Windows then you'd use CreateToolhelp32Snapshot(), followed by Process32First and Process32Next to iterate the running processes. Beware of the inevitable race condition, the process could have exited by the time you found it.
I just created one using Hans suggestion. Works like a champ!
Oh and here is the basic code.
Please you will have to add CStrings sAppPath and sAppName.
StartProcess is a small function that uses CreateProcess and returns the PID(not used here). You will need to replace it.
This is not a complete program, just the code to find if the program is running using Hans suggestion. A fun test is to set the path to c:\windows\ and the app to notepad.exe and set it for 10 seconds.
#include <tlhelp32.h>
PROCESSENTRY32 pe32 = {0};
HANDLE hSnap;
int iDone;
int iTime = 60;
bool bProcessFound;
while(true) // go forever
{
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
pe32.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnap,&pe32); // Can throw away, never an actual app
bProcessFound = false; //init values
iDone = 1;
while(iDone) // go until out of Processes
{
iDone = Process32Next(hSnap,&pe32);
if (strcmp(pe32.szExeFile,sAppName) == 0) // Did we find our process?
{
bProcessFound = true;
iDone = 0;
}
}
if(!bProcessFound) // if we didn't find it running...
{
startProcess(sAppPath+sAppName,""); // start it
}
Sleep(iTime*1000); // delay x amount of seconds.
}
Assumptions: since you mention '.exe', you want this for some flavor of Windows. You want to write a program in C++ to determine whether a program with a particular executable name is running (regardless of the language used to implement the target program).
Enumerate the running processes using either the Toolhelp API or the process status API. Compare the name of the executable for each running process to the one you're looking for (and be aware that there may be more than one process with that executable name).
hProcessInfo = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );
do{
if(strcmp(pe32.szExeFile,"process.exe") == 0)
{
processfound = true;
break;
}
}while( Process32Next( hProcessSnap, &pe32 ) );
If you don't want to get process detail from code just press Ctrl+Alt+Del and check process list.