Just installed AfterStep (as I have never heard of it!). Seems to work for me:
[xircon@localhost ~]$ pidof afterstep
[xircon@localhost ~]$ pidof gnome-session
The pid will always be different for each session of the same DE. You can test that by a logout/login and then run the command again.
One could do a
ps -ef |grep X|wc -l
where X is a placeholder for the DE and the result is 2 or larger for a given DE. To detect a given DE replace X with (DE in parenthesis): afterstep (afterstep), blackbox (blackbox), enlightenment (e17), fluxbox (fluxbox), metacity (Gnome), icewm (IceWM), kdeinit4 (KDE), lx (LXDE), openbox (OpenBox), pekwm (PekWM), xfce4 (XFCE). So for example to detect Gnome:
ps -ef |grep metacity|wc -l
The problem here is that this will only work if no other applications are running, as they will influence the counting. For example if you open a lxterminal in KDE and then check for LXDE the above command will output 2, so it can not be used in this case.
wmctrl still seems to be the safest option for me, maybe combined with $DESKTOP_SESSION