A line in the lstlisting environment cannot start with "\end{frame}" in a beamer presentation

beamer does a lot of leg work when setting the frame environment, since it might have to parse the contents more than once in order to take seemingly single slides and break them into number of frames. As a safe bet, you can box the contents of your listing outside the frame and then include the pre-typeset box:

enter image description here

\documentclass{beamer}% http://ctan.org/pkg/beamer
\usepackage{listings}% http://ctan.org/pkg/listings
\lstset{language=[LaTeX]tex}
\newsavebox{\codebox}% For storing listings

\begin{document}

\begin{lrbox}{\codebox}
\begin{lstlisting}
\begin{frame}
\titlepage
\end{frame}
\end{lstlisting}
\end{lrbox}

\begin{frame}
\usebox{\codebox}
\end{frame}

\end{document}​

If you use the "containsverbatim" option instead of "fragile" your minimal example works:

\begin{frame}[containsverbatim]{test}
\begin{lstlisting}
\begin{frame}
\titlepage
\end{frame}
\end{lstlisting}
\end{frame}

I found the solution in this post: https://stackoverflow.com/questions/2981008/latex-issue-with-beamer-and-listings