How to link between MongoDB C Driver to my own programs - c

I'm a novice user for MongoDB using C driver, and I can't find any detail tutorial that teach how to create my first MongoDB program in C.
I've created my first program according to http://api.mongodb.org/c/current/tutorial.html
#include <stdio.h>
#include "mongo.h"
int main() {
mongo conn[1];
int status = mongo_connect( conn, "127.0.0.1", 27017 );
if( status != MONGO_OK ) {
switch ( conn->err ) {
case MONGO_CONN_SUCCESS: printf( "connection succeeded\n" ); break;
case MONGO_CONN_NO_SOCKET: printf( "no socket\n" ); return 1;
case MONGO_CONN_FAIL: printf( "connection failed\n" ); return 1;
case MONGO_CONN_NOT_MASTER: printf( "not master\n" ); return 1;
}
}
mongo_destroy( conn );
return 0;
}
However, it shows up an error that it can not find where "mongo.h" is.
Does anyone know how to compile this file so I can link it to the MongoDB C driver?

You should go to C Language Driver docs and download the latest stable code base (v0.4).
This contains mongo.h. Install it where-ever you want on your computer, and build the library. You then need to specify the -I to the location of your downloaded headers, and -L for your compiled library.

Related

Intel-TSX: Why rtm is failing?

I'm new in using Intel-TSX. So, please correct me on any terminological/conceptional mistake.
I'm trying to write a custom rsa engine using a polarssl library from here (I know it is old, but I found it easy to understand). I have the following code,
result=-1;
unsigned block;
int key_len= 128;
while(result!=1){
if ((block = _xbegin()) == _XBEGIN_STARTED) {
if( rsa_pkcs1_decrypt( &rsa_polar, &myrand, NULL, RSA_PRIVATE, &key_len, from, decrypt_plaintext, sizeof(decrypt_plaintext) ) != 0 )
exit(0);
rsa_free(&rsa_polar);
result=1;
_xend();
}else{
printf("RTM 2: Transaction failed\n");
printf("status is %ld\n", block);
}
printf("Block 2: Result is %d\n", result);
}
The code inside the rtm block doesn't work. However, the same code works outside rtm block. Upon running the code I'm getting the following output,
.
.
RTM 2: Transaction failed
status is 0
Block 2: Result is -1
.
.
Any help/suggestions on how to solve it?

Develop C with multiple main entry points

I used to develop Java project by Eclipse.
A Java project can contain many code files with the main function (the entry point), so we can run each code file which has a main function.
But now I want to develop C project by Eclipse CDT.
In a C project we can have only one main function. Can I have many code files with a main function and run each file just like I would in Java?
P.S.: I don't like to write Make Target for each file by main self
Javas option to have a main in every object is highly irritating and does not make sense to me.
I assume you want to train a bit in c and want to find a way to have all training lessons in one file. Here is an option that would do that for you in a crude way. This would not be reasonable to do as an application but you can use this to execute different options.
To use this you would call your program like 'progname 1'.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int ProgrammingLesson001(void);
int main(int argc, char * argv[])
{
int i;
int option;
int e = 0;
printf("%i\n", argc);
for(i = 0; i < argc; ++i)
{
printf("%s\n", argv[i]);
}
if(2 == argc)
{
option = atoi(argv[1]);
printf("Your Option was '%s' interpreted as %i\n", argv[1], option);
}
else
{
option = 0;
e |= 1;
}
switch(option)
{
case 0:
printf("zero is an error\n");
e |= 1;
break;
case 1:
e |= ProgrammingLesson001();
break;
default:
break;
}
if(0 != e)
{
printf("an error has occureed\n");
}
return e;
}
int ProgrammingLesson001(void)
{
printf("This could behave like a main for training purposes\n");
}
If you spent some time programming in c take a second look at makefiles.
You can create a makefile that will fit all your programs.
This reduces the actual work you need to put into this so much that maintaining the switch construct is harder than creating a new project.
Thank Clifford to fixed my quest and guys who replied
I have solved this problem by myself
Here is my solution:
#!/bin/bash
SourceFile=$1
Path="$(dirname "$SourceFile")"
ParentPath="$(dirname "$Path")"
OutputPath="$ParentPath/bin"
OutputFile="$OutputPath/a.out"
mkdir -p $OutputPath
rm -f $OutputFile
gcc -w $SourceFile -lm -o $OutputFile
$OutputFile
This bash's name is gcc.sh
In eclipse run -> external tools -> external tools configurations -> new a configuration
Location: /home/xxxxx/gcc.sh
Working Directory: (just let it be empty)
arguments: ${resource_loc}
Then you can run C file by your customize command

Cleaned up camera osx and opencv

hi guys i am executing some sample programs at my macbook using opencv and this is my code:
#include "stdio.h"
#include "cv.h"
#include "highgui.h"
int main( int argc, char **argv )
{
CvCapture *capture = 0;
IplImage *frame = 0;
int key = 0;
/* initialize camera */
capture = cvCaptureFromCAM( 0 );
/* always check */
if ( !capture ) {
fprintf( stderr, "Cannot open initialize webcam!\n" );
return 1;
}
/* create a window for the video */
cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );
while(1>0)
{
/* get a frame */
frame = cvQueryFrame( capture );
/* always check */
if(!frame ) break;
/* display current frame */
cvShowImage( "result", frame );
waitKey(10);
/* exit if user press 'Esc' */
key = cvWaitKey( 20 );
if((char)key==27 )
break;
}
/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "result" );
return 0;
}
the code was working fine on the Macbookpro about a year ago ( OSX snow leopard ) but at the macbook (lion) i only get this at the console: Cleaned up camera. No isight, no image... nothing, only that message? any advise o.0?
ps? i changed the number at Caoture FromCAM to 300 ( iEEE cameras ) or 500 (quicktime ) then i have no message but still no image.
Never mind guys, apparently is an issue on the current opencv version 2.6.x. I unistalled ffmpeg brew uninstall ffmepg and opencv brew uninstall opencv
then i changed my opencv version cd /usr/local/Library/Taps/homebrew-science i searched other version ( isight was working under 4.5.5 ) brew versions opencv and i added the 2.4.5 git chekout ae74fe9 opencv.rb finally i installed opencv using brew install opencv and it is done isight works great :).
ps: isight camera will work with cvCaptureFromCAM( 500 ) not 0, -1 or 300.
ps2: omg i am so happy :3

C library gives '__gxx_personality_v0 ' error in Postgres

I'm building a new 64bit Debian Squeeze server, and Postgres 8.4 reports the well documented 'undefined __gxx_personality_v0' error when I try to restore a database.
The lib builds/installs fine.
However, the source is c, not c++ which seems to be where __gxx_personality_v0 belongs.
The code is from a 32bit Etch/postgres 8.1 environmnet.
I'm kind of stuck - but I bet the solution is very simple!
Test to see whether the issue is actually related to PostgreSQL, or if it is a problem with your library build. Here's a simple program you can use to dlopen() your library and resolve a symbol. Compile it with:
gcc dlopentest.c -o dlopentest -ldl
... and run it as:
./dlopentest /path/to/my/lib.so somesymbol
or for more info prefix LD_DEBUG=symbols (for other options LD_DEBUG=help) eg:
LD_DEBUG=symbols ./dlopentest /path/to/my/lib somesymbol
Which symbol to look for depends on your code and what it's for. You haven't provided enough information to say.
This test program won't work with any library that requires symbols from the postgresql executable in order to load and init, so if your code is (for example) a procedural language it won't load. Most simple modules load fine, though.
You should also examine the output of:
ldd /path/to/your/library.so
to see if it's linking to libstdc++ or anything else you don't expect.
Here's the test program:
// Compile with a c99 compiler; I don't use oldstyle declarations
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char * argv[]) {
if (argc != 3) {
printf("Usage: %s /path/to/lib/to/load symbol_to_resolve\n", argv[0]);
printf(" eg: %s libc.so.6 gettimeofday\n", argv[0]);
return 1;
}
char * err;
const char * const libname = argv[1];
const char * const symname = argv[2];
dlerror(); // clear dl error state before starting work
void * libhandle = dlopen(libname, RTLD_LAZY);
if ( (err = dlerror()) != NULL ) {
printf("Failed to load library: %s\n", err);
return 2;
}
void * symhandle = dlsym(libhandle, symname);
if ( (err = dlerror()) != NULL ) {
printf("Failed to load symbol: %s\n", err);
return 2;
}
printf("Successfully retrieved symbol %s from library %s\n", symname, libname);
// Optional since we're existing, but good for testing:
if ( (err = dlerror()) != NULL ) {
printf("Failed to close lib during exit: %s\n", err);
return 2;
}
return 0;
}

What is the Windows equivalent of "pidof" from Linux?

In a batchscript, I need to get a list of process IDs with given binary path C:\path\to\binary.exe.
In Linux, I can just do pidof /path/to/binary.
Is there a Win32 executable which does the same, supported from WinXP Home to Win7 (tasklist won't work)?
The package which includes this has to be portable, so a 10MB download is not what I'm looking for.
Is there a C function available which does this and is supported from WinXP to Win7? Note: I want to match a process path, not a filename which could be used by other applications too.
wmic.exe is available on XP, Vista and 7 and can do this. However, it does not come with Windows XP Home edition.
wmic process where ExecutablePath='C:\\windows\\system32\\notepad.exe' get ProcessId
If you want support for Windows XP Home too, you can use EnumProcess and GetModuleFileNameEx. The downside here is that you won't be able to query names of processes running by another user if you're not running as administrator. QueryFullProcessImageName will probably do the trick here, but it's Vista+.
If that's not enough, you'll need Process32First (swatkat's code). For each process you need to call Module32First and then get MODULEENTRY32->szExePath. Note that even this is not completely portable and will not work well on x64 where you'll need QueryFullProcessImageName.
You can use Toolhelp APIs to enumerate processes, get their full path and compare it with the required process name. You need to walk the modules list for each process. The first module in the list is the process executable itself. Here's a sample code:
int main( int argc, char* argv[] )
{
if( argc > 1 )
{
printf( "\nGetting PID of: %s\n", argv[1] );
HANDLE hProcSnapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( INVALID_HANDLE_VALUE != hProcSnapshot )
{
PROCESSENTRY32 procEntry = {0};
procEntry.dwSize = sizeof(PROCESSENTRY32);
if( ::Process32First( hProcSnapshot, &procEntry ) )
{
do
{
HANDLE hModSnapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, procEntry.th32ProcessID );
if( INVALID_HANDLE_VALUE != hModSnapshot )
{
MODULEENTRY32 modEntry = {0};
modEntry.dwSize = sizeof( MODULEENTRY32 );
if( Module32First( hModSnapshot, &modEntry ) )
{
if( 0 == stricmp( argv[1], modEntry.szExePath ) )
{
printf( "\nPID: %ld\n", procEntry.th32ProcessID );
::CloseHandle( hModSnapshot );
break;
}
}
::CloseHandle( hModSnapshot );
}
}
while( ::Process32Next( hProcSnapshot, &procEntry ) );
}
::CloseHandle( hProcSnapshot );
}
}
return 0;
}
You can write a small C# application which first calls Process.GetProcessesByName(String) , then go over the results and print the Id property of each one when the MainModule.FileName is equal to the path you are looking for.
PowerShell can solve your problems, if is buit in in Win 7, and downloadable on the other OSs.
param($fileName)
Get-Process | where -FilterScript {$_.MainModule.FileName -eq $fileName}
This script will receive one parameter, the filename you are looking for, and it will output the filename of its executable.
You can call this from a bat file by doing:
powershell -Command "& {Get-Process | where -FilterScript {$_.MainModule.FileName -eq %FILENAME%}"

Resources